Transform the backbone module into a trainer module.
(self, mod: IRModule, ctx: tvm.transform.PassContext)
| 171 | ) |
| 172 | |
| 173 | def transform_module(self, mod: IRModule, ctx: tvm.transform.PassContext) -> IRModule: |
| 174 | """Transform the backbone module into a trainer module.""" |
| 175 | self._check_well_formed(mod) |
| 176 | |
| 177 | mod = AppendLoss( |
| 178 | self.BACKBONE_FUNC, |
| 179 | self._loss(*self._loss_args), # type: ignore |
| 180 | self._loss.num_backbone_outputs, |
| 181 | self.BACKBONE_LOSS_FUNC, |
| 182 | )(mod) |
| 183 | |
| 184 | # Decompose batch_norm operator, which behaves differently in inference and training stages |
| 185 | mod = DecomposeOpsForInference(self.BACKBONE_FUNC)(mod) |
| 186 | mod = DecomposeOpsForTraining(self.BACKBONE_LOSS_FUNC)(mod) |
| 187 | |
| 188 | # Gradient pass. |
| 189 | param_num = int(mod.attrs[self.PARAM_NUM_ATTR_KEY]) |
| 190 | state_num = int(mod.attrs[self.STATE_NUM_ATTR_KEY]) |
| 191 | input_num = len(mod[self.BACKBONE_FUNC].params) - param_num - state_num |
| 192 | params = mod[self.BACKBONE_LOSS_FUNC].params[input_num : input_num + param_num] |
| 193 | mod = Gradient(self.BACKBONE_LOSS_FUNC, require_grads=params, target_index=0)(mod) |
| 194 | |
| 195 | # Add optimizer function. |
| 196 | self._optimizer.init(params) |
| 197 | # Need the global symbol to match the function's name |
| 198 | mod[self.OPTIMIZER_FUNC] = self._optimizer.get_function().with_attr( |
| 199 | "global_symbol", self.OPTIMIZER_FUNC |
| 200 | ) |
| 201 | |
| 202 | # Module attrs |
| 203 | mod = mod.with_attrs( |
| 204 | { |
| 205 | "input_num": input_num, |
| 206 | "optim_state": self._optimizer.state, |
| 207 | } |
| 208 | ) |
| 209 | |
| 210 | if self._legalize: |
| 211 | mod = LegalizeOps()(mod) |
| 212 | |
| 213 | return mod |
nothing calls this directly
no test coverage detected