| 1 | import torch.nn as nn |
| 2 | |
| 3 | class DistillModel(nn.Module): |
| 4 | def __init__(self, teacher, student): |
| 5 | super().__init__() |
| 6 | self.teacher = teacher |
| 7 | self.student = student |
| 8 | |
| 9 | def forward(self, teacher_kwargs, student_kwargs): |
| 10 | teacher_logits, *mem_t = self.teacher(**teacher_kwargs) |
| 11 | student_logits, *mem_s = self.student(**student_kwargs) |
| 12 | return teacher_logits, student_logits |
| 13 | |
| 14 | def disable_untrainable_params(self): |
| 15 | for n, p in self.teacher.named_parameters(): |
| 16 | p.requires_grad_(False) |
| 17 | |
| 18 | @classmethod |
| 19 | def add_model_specific_args(cls, parser): |
| 20 | group = parser.add_argument_group('BERT-distill', 'BERT distill Configurations') |
| 21 | group.add_argument('--teacher', type=str) |
| 22 | group.add_argument('--tc-type', type=str) |
| 23 | group.add_argument('--st-type', type=str) |
| 24 | return parser |
| 25 | |
| 26 | @classmethod |
| 27 | def from_pretrained(cls, args, teacher_cls, student_name, student_cls): |
| 28 | student, args = student_cls.from_pretrained(student_name, args, prefix='student.') |
| 29 | if isinstance(teacher_cls, type): |
| 30 | teacher, t_args = teacher_cls.from_pretrained(args.teacher, args) |
| 31 | else: |
| 32 | teacher = teacher_cls |
| 33 | model = DistillModel(teacher, student) |
| 34 | return model, args |
no outgoing calls
no test coverage detected