{"record":{"id":"458af9e712750d1e","repo":"ultralytics/yolov5","slug":"no-matching-tensorflow-activation-found-for-pytorc","errorCode":null,"errorMessage":"no matching TensorFlow activation found for PyTorch activation {act}","messagePattern":"no matching TensorFlow activation found for PyTorch activation (.+?)","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"models/tf.py","lineNumber":704,"sourceCode":"            selected_classes,\n            paddings=[[0, topk_all - tf.shape(selected_boxes)[0]]],\n            mode=\"CONSTANT\",\n            constant_values=-1.0,\n        )\n        valid_detections = tf.shape(selected_inds)[0]\n        return padded_boxes, padded_scores, padded_classes, valid_detections\n\n\ndef activations(act=nn.SiLU):\n    \"\"\"Converts PyTorch activations to TensorFlow equivalents, supporting LeakyReLU, Hardswish, and SiLU/Swish.\"\"\"\n    if isinstance(act, nn.LeakyReLU):\n        return lambda x: keras.activations.relu(x, alpha=0.1)\n    elif isinstance(act, nn.Hardswish):\n        return lambda x: x * tf.nn.relu6(x + 3) * 0.166666667\n    elif isinstance(act, (nn.SiLU, SiLU)):\n        return lambda x: keras.activations.swish(x)\n    else:\n        raise TypeError(f\"no matching TensorFlow activation found for PyTorch activation {act}\")\n\n\ndef representative_dataset_gen(dataset, ncalib=100):\n    \"\"\"Generate representative dataset for calibration by yielding transformed numpy arrays from the input dataset.\"\"\"\n    for n, (path, img, im0s, vid_cap, string) in enumerate(dataset):\n        im = np.transpose(img, [1, 2, 0])\n        im = np.expand_dims(im, axis=0).astype(np.float32)\n        im /= 255\n        yield [im]\n        if n >= ncalib:\n            break\n\n\ndef run(\n    weights=ROOT / \"yolov5s.pt\",  # weights path\n    imgsz=(640, 640),  # inference size h,w\n    batch_size=1,  # batch size\n    dynamic=False,  # dynamic batch size","sourceCodeStart":686,"sourceCodeEnd":722,"githubUrl":"https://github.com/ultralytics/yolov5/blob/20d1d78a08277e365d57bfa3a2cce752772d9e59/models/tf.py#L686-L722","documentation":"models/tf.py activations() raises TypeError when asked to convert a PyTorch activation module that has no mapped TensorFlow equivalent. Only nn.LeakyReLU, nn.Hardswish, and nn.SiLU/SiLU are handled; any other activation (nn.ReLU, nn.Mish, nn.ELU, ...) reaches the else branch. This function is used while building the Keras/graph copy of a model for TF exports, so the error surfaces during export, not training.","triggerScenarios":"Exporting a custom YOLOv5 variant whose YAML/blocks use nn.ReLU or nn.Mish activations via export.py --include saved_model/tflite/pb; loading a third-party checkpoint with unusual activation modules and converting it to TF.","commonSituations":"Custom architectures (mish-variant YOLO forks); ablation experiments swapping activation functions; trying to export classification heads with nn.ELU.","solutions":["Retrain/convert with a supported activation (SiLU is the YOLOv5 default) if you do not control the export code.","Extend the mapping in models/tf.py activations() with an equivalent TF op for your activation (see exampleFix).","Export to a backend that does not need the TF graph copy (onnx, engine) as a workaround."],"exampleFix":"# before\nelse:\n    raise TypeError(f\"no matching TensorFlow activation found for PyTorch activation {act}\")\n\n# after (add a branch before the else)\nelif isinstance(act, nn.ReLU):\n    return lambda x: tf.nn.relu(x)\nelse:\n    raise TypeError(f\"no matching TensorFlow activation found for PyTorch activation {act}\")","handlingStrategy":"fallback","validationCode":"import torch.nn as nn\n\nUNSUPPORTED = (nn.ReLU, nn.ELU, nn.PReLU, nn.GELU, nn.SELU, nn.CELU, nn.Tanh, nn.Softplus, nn.Softsign)\n\ndef model_acts_exportable(model) -> bool:\n    \"\"\"True if every activation module has a TF mapping in models/tf.py.\"\"\"\n    return not any(isinstance(m, UNSUPPORTED) for m in model.modules())","typeGuard":"import torch.nn as nn\n\nUNSUPPORTED = (nn.ReLU, nn.ELU, nn.PReLU, nn.GELU, nn.SELU, nn.CELU, nn.Tanh, nn.Softplus, nn.Softsign)\n\ndef activations_convertible(model: nn.Module) -> bool:\n    \"\"\"True if no activation module lacks a TF mapping in models/tf.py activations().\"\"\"\n    return not any(isinstance(m, UNSUPPORTED) for m in model.modules())","tryCatchPattern":"try:\n    keras_act = activations(type(m))\nexcept TypeError:\n    keras_act = keras.activations.relu  # conservative fallback for exports","preventionTips":["Stick to SiLU/LeakyReLU (YOLOv5 defaults) for models destined for TF export.","Smoke-test the TF export right after training, not at deploy time."],"tags":["export","tensorflow","activations","custom-model"],"backgroundTag":null,"analyzedSha":"20d1d78a08277e365d57bfa3a2cce752772d9e59","analyzedAt":"2026-08-15T02:56:15.443Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}