ultralytics/yolov5 · error · TypeError
no matching TensorFlow activation found for PyTorch activati
Error message
no matching TensorFlow activation found for PyTorch activation {act} What it means
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.
Source
Thrown at models/tf.py:704
selected_classes,
paddings=[[0, topk_all - tf.shape(selected_boxes)[0]]],
mode="CONSTANT",
constant_values=-1.0,
)
valid_detections = tf.shape(selected_inds)[0]
return padded_boxes, padded_scores, padded_classes, valid_detections
def activations(act=nn.SiLU):
"""Converts PyTorch activations to TensorFlow equivalents, supporting LeakyReLU, Hardswish, and SiLU/Swish."""
if isinstance(act, nn.LeakyReLU):
return lambda x: keras.activations.relu(x, alpha=0.1)
elif isinstance(act, nn.Hardswish):
return lambda x: x * tf.nn.relu6(x + 3) * 0.166666667
elif isinstance(act, (nn.SiLU, SiLU)):
return lambda x: keras.activations.swish(x)
else:
raise TypeError(f"no matching TensorFlow activation found for PyTorch activation {act}")
def representative_dataset_gen(dataset, ncalib=100):
"""Generate representative dataset for calibration by yielding transformed numpy arrays from the input dataset."""
for n, (path, img, im0s, vid_cap, string) in enumerate(dataset):
im = np.transpose(img, [1, 2, 0])
im = np.expand_dims(im, axis=0).astype(np.float32)
im /= 255
yield [im]
if n >= ncalib:
break
def run(
weights=ROOT / "yolov5s.pt", # weights path
imgsz=(640, 640), # inference size h,w
batch_size=1, # batch size
dynamic=False, # dynamic batch sizeView on GitHub (pinned to 20d1d78a08)
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.
Example fix
# before
else:
raise TypeError(f"no matching TensorFlow activation found for PyTorch activation {act}")
# after (add a branch before the else)
elif isinstance(act, nn.ReLU):
return lambda x: tf.nn.relu(x)
else:
raise TypeError(f"no matching TensorFlow activation found for PyTorch activation {act}") Defensive patterns
Strategy: fallback
Validate before calling
import torch.nn as nn
UNSUPPORTED = (nn.ReLU, nn.ELU, nn.PReLU, nn.GELU, nn.SELU, nn.CELU, nn.Tanh, nn.Softplus, nn.Softsign)
def model_acts_exportable(model) -> bool:
"""True if every activation module has a TF mapping in models/tf.py."""
return not any(isinstance(m, UNSUPPORTED) for m in model.modules()) Type guard
import torch.nn as nn
UNSUPPORTED = (nn.ReLU, nn.ELU, nn.PReLU, nn.GELU, nn.SELU, nn.CELU, nn.Tanh, nn.Softplus, nn.Softsign)
def activations_convertible(model: nn.Module) -> bool:
"""True if no activation module lacks a TF mapping in models/tf.py activations()."""
return not any(isinstance(m, UNSUPPORTED) for m in model.modules()) Try / catch
try:
keras_act = activations(type(m))
except TypeError:
keras_act = keras.activations.relu # conservative fallback for exports Prevention
- Stick to SiLU/LeakyReLU (YOLOv5 defaults) for models destined for TF export.
- Smoke-test the TF export right after training, not at deploy time.
When it happens
Trigger: 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.
Common situations: Custom architectures (mish-variant YOLO forks); ablation experiments swapping activation functions; trying to export classification heads with nn.ELU.
Related errors
AI-assisted analysis of ultralytics/yolov5@20d1d78a08 (2026-08-15).
Data as JSON: /api/errors/458af9e712750d1e.
Report an issue: GitHub.