(
model: nn.Module, inputs: list, mode: str, **kwargs
)
| 118 | |
| 119 | |
| 120 | def _wrapper_count_operators( |
| 121 | model: nn.Module, inputs: list, mode: str, **kwargs |
| 122 | ) -> typing.DefaultDict[str, float]: |
| 123 | |
| 124 | # ignore some ops |
| 125 | supported_ops = {k: lambda *args, **kwargs: {} for k in _IGNORED_OPS} |
| 126 | supported_ops.update(kwargs.pop("supported_ops", {})) |
| 127 | kwargs["supported_ops"] = supported_ops |
| 128 | |
| 129 | assert len(inputs) == 1, "Please use batch size=1" |
| 130 | tensor_input = inputs[0]["image"] |
| 131 | |
| 132 | class WrapModel(nn.Module): |
| 133 | def __init__(self, model): |
| 134 | super().__init__() |
| 135 | if isinstance( |
| 136 | model, (nn.parallel.distributed.DistributedDataParallel, nn.DataParallel) |
| 137 | ): |
| 138 | self.model = model.module |
| 139 | else: |
| 140 | self.model = model |
| 141 | |
| 142 | def forward(self, image): |
| 143 | # jit requires the input/output to be Tensors |
| 144 | inputs = [{"image": image}] |
| 145 | outputs = self.model.forward(inputs) |
| 146 | # Only the subgraph that computes the returned tuple of tensor will be |
| 147 | # counted. So we flatten everything we found to tuple of tensors. |
| 148 | return _flatten_to_tuple(outputs) |
| 149 | |
| 150 | old_train = model.training |
| 151 | with torch.no_grad(): |
| 152 | if mode == FLOPS_MODE: |
| 153 | ret = flop_count(WrapModel(model).train(False), (tensor_input,), **kwargs) |
| 154 | elif mode == ACTIVATIONS_MODE: |
| 155 | ret = activation_count(WrapModel(model).train(False), (tensor_input,), **kwargs) |
| 156 | else: |
| 157 | raise NotImplementedError("Count for mode {} is not supported yet.".format(mode)) |
| 158 | # compatible with change in fvcore |
| 159 | if isinstance(ret, tuple): |
| 160 | ret = ret[0] |
| 161 | model.train(old_train) |
| 162 | return ret |
no test coverage detected