Ë
    éÓ^j~;  ã                   óÒ   — d Z ddlZddlmZmZmZ ddlZddlmZ ddl	mc m
Z ddlmZ ddlmZ ddlmZ  ej$                  e«      Z G d„ d	ej*                  «      Z G d
„ de«      Zy)zJToken-based distillation training task for models with distillation heads.é    N)ÚDictÚOptionalÚUnion)Úcreate_model)Úunwrap_modelé   )ÚTrainingTaskc                   óx  ‡ — e Zd ZdZ	 	 	 	 	 ddeeej                  f   dee	   de	dee   dee
j                     dee
j                     fˆ fd„Z	 	 dd	ed
ee   dd fd„Zde
j                  de
j                  fd„Z	 	 dde
j                  dee
j                     dee
j                     de
j                  fd„Zˆ xZS )ÚTokenDistillationTeacheraK  Wrapper for a teacher model used in token-based distillation.

    Creates and manages a pre-trained teacher model for token distillation,
    handling model creation and normalization differences between teacher and student.

    Can be created from:
    - A model name string (creates the model internally)
    - An existing nn.Module (wraps it with the necessary interface)

    Args:
        model_name_or_module: Either a model name string or an nn.Module
        num_classes: Number of output classes (required if model_name_or_module is a string)
        in_chans: Number of input channels (used if model_name_or_module is a string)
        pretrained_path: Optional path to pretrained weights (used if model_name_or_module is a string)
        device: Device to place the model on
        dtype: Model dtype (uses float32 if None)
    Úmodel_name_or_moduleÚnum_classesÚin_chansÚpretrained_pathÚdeviceÚdtypec           	      ó  •— t         ‰| �  «        t        |t        «      rAt        j                  d|› d�«       ddi}|rt        ||¬«      |d<   t        d|||||dœ|¤Ž}n>t        |t        j                  «      r|}n!t        dt        |«      j                  › �«      ‚|j                  «        || _        t        |«      }	t!        |	d	«      r9|	j"                  j%                  d
d«      }
|	j"                  j%                  dd«      }nd}
d}t'        j(                  |
||¬«      j+                  dddd«      }t'        j(                  |||¬«      j+                  dddd«      }| j-                  d|d¬«       | j-                  d|d¬«       y )Nz,Creating token distillation teacher model: 'ú'Ú
pretrainedT)Úfiler   Úpretrained_cfg_overlay)Ú
model_namer   r   r   r   z8model_name_or_module must be a string or nn.Module, got Úpretrained_cfgÚmean)g
×£p=
ß?gÉv¾Ÿ/Ý?g–C‹lçûÙ?Ústd)gZd;ßOÍ?gyé&1¬Ì?gÍÌÌÌÌÌÌ?©r   r   r   éÿÿÿÿÚmean_kdF©Ú
persistentÚstd_kd© )ÚsuperÚ__init__Ú
isinstanceÚstrÚ_loggerÚinfoÚdictr   ÚnnÚModuleÚ	TypeErrorÚtypeÚ__name__ÚevalÚmodelr   Úhasattrr   ÚgetÚtorchÚtensorÚviewÚregister_buffer)Úselfr   r   r   r   r   r   Úpretrained_kwargsr/   Úmodel_unwrappedr   r   r   r    Ú	__class__s                 €úg/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/timm/task/token_distillation.pyr#   z!TokenDistillationTeacher.__init__$   s“  ø€ ô 	‰ÑÔäÐ*¬CÔ0Ü�L‰LÐGÐH\ÐG]Ð]^Ð_Ô`à!-¨tÐ 4ÐÙÜ>BØ(Ø +ô?Ð!Ð":Ñ;ô
 !ð Ø/Ø'Ø!ØØñð $ñ‰Eô Ð,¬b¯i©iÔ8Ø(‰EäØJÌ4ÐPdÓKe×KnÑKnÐJoÐpóð ð 	�
‰
ŒØˆŒ
ô ' uÓ-ˆÜ�?Ð$4Ô5Ø"×1Ñ1×5Ñ5°fÐ>SÓTˆDØ!×0Ñ0×4Ñ4°UÐ<QÓR‰Cà(ˆDØ'ˆCä—,‘,˜t¨F¸%Ô@×EÑEÀaÈÈQÐPQÓRˆÜ—‘˜c¨&¸Ô>×CÑCÀAÀrÈ1ÈaÓPˆØ×Ñ˜Y¨¸EÐÔBØ×Ñ˜X v¸%ÐÕ@ó    ÚbackendÚmodeÚreturnc                 óV   — t        j                  | j                  f||dœ|¤Ž| _        | S )z Compile teacher logit inference.©r<   r=   )r2   Úcompiler/   ©r6   r<   r=   Úcompile_kwargss       r:   rA   z TokenDistillationTeacher.compileY   s)   € ô —]‘] 4§:¡:Ð\°wÀTÑ\È^Ñ\ˆŒ
Øˆr;   Úinputc                 ó$   — | j                  |«      S )z³Forward pass through teacher model.

        Args:
            input: Input tensor (should already be normalized for teacher)

        Returns:
            Teacher logits
        )r/   )r6   rD   s     r:   Úforwardz TokenDistillationTeacher.forwardc   s   € ð �z‰z˜%Ó Ð r;   Ústudent_meanÚstudent_stdc                 óÖ   — |�|€|S t        j                  || j                  «      r"t        j                  || j                  «      r|S ||z  |z   | j                  z
  | j                  z  S )ao  Normalize input to match teacher's expected normalization.

        Args:
            input: Input tensor (already normalized for student)
            student_mean: Student normalization mean buffer [1, 3, 1, 1]
            student_std: Student normalization std buffer [1, 3, 1, 1]

        Returns:
            Input tensor normalized for the teacher model
        )r2   Úequalr   r    )r6   rD   rG   rH   s       r:   Únormalize_inputz(TokenDistillationTeacher.normalize_inputn   sa   € ð  Ð ;Ð#6ØˆLÜ�;‰;�| T§\¡\Ô2´u·{±{À;ÐPT×P[ÑP[Ô7\ØˆLØ˜Ñ# lÑ2°T·\±\ÑAÀTÇ[Á[ÑPÐPr;   )Né   NNN©ÚinductorN)NN)r-   Ú
__module__Ú__qualname__Ú__doc__r   r%   r)   r*   r   Úintr2   r   r   r#   rA   ÚTensorrF   rK   Ú__classcell__©r9   s   @r:   r   r      s!  ø„ ñð* *.ØØ-1Ø-1Ø+/ñ3Aà"'¨¨R¯Y©Y¨Ñ"7ð3Að " #™ð3Að ð	3Að
 & c™]ð3Að ˜UŸ\™\Ñ*ð3Að ˜EŸK™KÑ(õ3Aðn &Ø"&ñàðð ˜3‘-ðð
 
$óð	!˜UŸ\™\ð 	!¨e¯l©ló 	!ð 48Ø26ñ	Qà—<‘<ðQð # 5§<¡<Ñ0ðQð " %§,¡,Ñ/ð	Qð
 
�‰÷Qr;   r   c                   ó   ‡ — e Zd ZdZ	 	 	 	 	 	 	 	 	 ddej
                  deeej
                  ef   de	ej
                     de	e   dede	e
   de	e
   d	e
d
e	ej                     de	ej                     defˆ fd„Z	 dde	e   dd fd„Z	 	 ddede	e   dej
                  fd„Zdej&                  dej&                  deeej&                  f   fd„Zˆ xZS )ÚTokenDistillationTaskaÄ  Token-based distillation task for models with distillation heads.

    For models like DeiT that have a dedicated distillation token/head that returns
    a tuple (main_logits, dist_logits) when distilled_training is enabled. The main
    head is trained against ground truth labels while the distillation head matches
    teacher outputs.

    Supports two distillation modes:
    - 'soft': KL divergence with temperature scaling (default)
    - 'hard': Cross-entropy with teacher's hard predictions (argmax)

    Loss weighting supports two modes:
    1. Independent weights: loss = task_loss_weight * task_loss + distill_loss_weight * distill_loss
    2. Complementary mode: loss = task_loss_weight * task_loss + (1 - task_loss_weight) * distill_loss
       (used when only task_loss_weight is specified)

    Args:
        student_model: Student model with set_distilled_training() method
        teacher_model: Teacher model - can be a model name string, nn.Module, or TokenDistillationTeacher
        criterion: Task loss function for main head (default: CrossEntropyLoss)
        teacher_pretrained_path: Path to teacher pretrained weights (used when teacher_model is a string)
        distill_type: 'soft' for KL-div or 'hard' for CE with teacher argmax
        distill_loss_weight: Weight for distillation loss
        task_loss_weight: Weight for task loss
        temperature: Softmax temperature for soft distillation (ignored for hard)
        device: Device for task tensors/buffers
        dtype: Dtype for task tensors/buffers
        verbose: Enable info logging

    Example:
        >>> # With model name string (num_classes/in_chans inferred from student)
        >>> task = TokenDistillationTask(
        ...     student_model=model, teacher_model='deit_base_patch16_224',
        ...     criterion=nn.CrossEntropyLoss(),
        ...     distill_type='soft', temperature=3.0, task_loss_weight=0.5,
        ...     device=torch.device('cuda'),
        ... )
        >>> # With raw model
        >>> task = TokenDistillationTask(
        ...     student_model=model, teacher_model=my_teacher_model,
        ...     criterion=nn.CrossEntropyLoss(),
        ...     distill_type='hard', task_loss_weight=0.5,
        ... )
    Ústudent_modelÚteacher_modelÚ	criterionÚteacher_pretrained_pathÚdistill_typeÚdistill_loss_weightÚtask_loss_weightÚtemperaturer   r   Úverbosec                 ó  •— t         ‰| �  |	|
|¬«       t        |«      }t        |d«      s#t	        d|j
                  j                  › d�«      ‚|j                  d«       t        |t        «      r|}n‰t        |t        «      st        |t        j                  «      r>|j                  }|j                  }t        ||||| j                  | j                   ¬«      }n!t#        dt%        |«      j                  › �«      ‚|| _        || _        |�|nt        j*                  «       | _        || _        || _        |dvrt	        d	|› d
�«      ‚t3        j4                  |j6                  d   | j                  | j                   ¬«      j9                  dddd«      }t3        j4                  |j6                  d   | j                  | j                   ¬«      j9                  dddd«      }| j;                  d|d¬«       | j;                  d|d¬«       |�D|| _        |�|nd| _        | j@                  r´tB        jE                  d| j>                  › d|› �«       nŽ|�C|| _        d|z
  | _        | j@                  rotB        jE                  d|› d| j<                  › �«       nId| _        d| _        | j@                  r/tB        jE                  d| j>                  › d| j<                  › �«       | j@                  rtB        jE                  d|› d|› �«       y y )N)r   r   r`   Úset_distilled_trainingzModel z� does not have 'set_distilled_training' method. TokenDistillationTask requires a model with a distillation head (e.g., DeiT distilled variants).T)r   r   r   r   r   r   zWteacher_model must be a model name string, nn.Module, or TokenDistillationTeacher, got )ÚsoftÚhardzUnsupported distill_type 'z'. Must be 'soft' or 'hard'.r   r   r   r   r   rG   Fr   rH   ç      ð?z9TokenDistillationTask: Independent weights - task_weight=z, distill_weight=z8TokenDistillationTask: Complementary mode - task_weight=z;TokenDistillationTask: Default equal weights - task_weight=z$TokenDistillationTask: distill_type=z, temperature=)#r"   r#   r   r0   Ú
ValueErrorr9   r-   rb   r$   r   r%   r)   r*   r   r   r   r   r+   r,   Útrainable_moduleÚteacherÚCrossEntropyLossrZ   r\   r_   r2   r3   r   r4   r5   r]   r^   r`   r&   r'   )r6   rX   rY   rZ   r[   r\   r]   r^   r_   r   r   r`   Ústudent_unwrappedrh   r   r   rG   rH   r9   s                     €r:   r#   zTokenDistillationTask.__init__³   s  ø€ ô 	‰Ñ ¨e¸WÐÔEô )¨Ó7ÐÜÐ(Ð*BÔCÜØÐ*×4Ñ4×=Ñ=Ð>ð ?sð sóð ð 	×0Ñ0°Ô6ô �mÔ%=Ô>Ø#‰GÜ˜¤sÔ+¬z¸-ÌÏÉÔ/Sà+×7Ñ7ˆKØ(×1Ñ1ˆHÜ.Ø%2Ø'Ø!Ø 7Ø—{‘{Ø—j‘jô‰Gô ðÜ˜MÓ*×3Ñ3Ð4ð6óð ð
 !.ˆÔØˆŒØ&/Ð&;™Ä×ATÑATÓAVˆŒØ(ˆÔØ&ˆÔàÐ/Ñ/ÜÐ9¸,¸ÐGcÐdÓeÐeô —|‘|Ø×,Ñ,¨VÑ4Ø—;‘;Ø—*‘*ô
÷ ‰$ˆq�"�a˜Ó
ð	 	ô
 —l‘lØ×,Ñ,¨UÑ3Ø—;‘;Ø—*‘*ô
÷ ‰$ˆq�"�a˜Ó
ð	 	ð
 	×Ñ˜^¨\ÀeÐÔLØ×Ñ˜]¨KÀEÐÔJð Ð*à':ˆDÔ$Ø8HÐ8TÑ$4ÐZ]ˆDÔ!Ø�|Š|Ü—‘ð#Ø#'×#8Ñ#8Ð"9Ð9JÐK^ÐJ_ðaõð Ð)à$4ˆDÔ!Ø'*Ð-=Ñ'=ˆDÔ$Ø�|Š|Ü—‘ð#Ø#3Ð"4Ð4EÀd×F^ÑF^ÐE_ðaõð (+ˆDÔ$Ø$'ˆDÔ!Ø�|Š|Ü—‘ð#Ø#'×#8Ñ#8Ð"9Ð9JÈ4×KcÑKcÐJdðfôð
 �<Š<Ü�L‰LØ6°|°nÀNÐS^ÐR_Ð`õð r;   Ú
device_idsr>   c                 ó’   — ddl m} | j                  j                  «       D ]	  }d|_        Œ  || j
                  fd|i|¤Ž| _        | S )aŒ  Prepare task for distributed training.

        Wraps the student model in DistributedDataParallel (DDP) while leaving
        the frozen teacher model unwrapped.

        Args:
            device_ids: List of device IDs for DDP (e.g., [local_rank])
            **ddp_kwargs: Additional arguments passed to DistributedDataParallel

        Returns:
            self (for method chaining)
        r   )ÚDistributedDataParallelFrk   )Útorch.nn.parallelrm   rh   Ú
parametersÚrequires_gradrg   )r6   rk   Ú
ddp_kwargsÚDDPÚparams        r:   Úprepare_distributedz)TokenDistillationTask.prepare_distributed  sQ   € õ" 	Eà—\‘\×,Ñ,Ó.ò 	(ˆEØ"'ˆEÕð	(ñ !$ D×$9Ñ$9Ñ _ÀjÐ _ÐT^Ñ _ˆÔØˆr;   r<   r=   c                 óÊ   — t        j                  | j                  f||dœ|¤Ž| _        | j                  | _         | j                  j                  d||dœ|¤Ž | j                  S )z=Compile student eval/train forward and teacher logit forward.r@   r!   )r2   rA   rg   Ú
eval_modelrh   rB   s       r:   rA   zTokenDistillationTask.compile5  s`   € ô !&§¡¨d×.CÑ.CÐ rÈWÐ[_Ñ rÐcqÑ rˆÔà×/Ñ/ˆŒØˆ�‰×ÑÐJ W°4ÑJ¸>ÒJØ×$Ñ$Ð$r;   rD   Útargetc                 óâ  — | j                  |«      }|\  }}| j                  ||«      }t        j                  «       5  | j                  j                  || j                  | j                  «      }| j	                  |j                  «       «      }ddd«       | j                  dk(  rrt        j                  || j                  z  d¬«      }	t        j                  | j                  z  d¬«      }
t        j                  |	|
dd¬«      | j                  dz  z  }n(j                  d¬«      }t        j                  ||«      }| j                   |z  | j"                  |z  z   }||||d	œS # 1 sw Y   ŒØxY w)
aÂ  Forward pass with token distillation.

        Args:
            input: Input tensor [B, C, H, W]
            target: Target labels [B]

        Returns:
            Dictionary containing:
                - 'loss': Combined training loss (task + distillation)
                - 'output': Main head logits (for metrics)
                - 'task_loss': Classification loss component
                - 'distill_loss': Distillation loss component
        Nrc   r   )ÚdimÚ	batchmeanT)Ú	reductionÚ
log_targeté   )ÚlossÚoutputÚ	task_lossÚdistill_loss)rg   rZ   r2   Úno_gradrh   rK   rG   rH   Údetachr\   ÚFÚlog_softmaxr_   Úkl_divÚargmaxÚcross_entropyr^   r]   )r6   rD   rw   Ústudent_outputÚmain_logitsÚdist_logitsr€   Úinput_kdÚteacher_logitsÚprob_sÚprob_tr�   Úteacher_hardÚ
total_losss                 r:   rF   zTokenDistillationTask.forwardB  sR  € ð& ×.Ñ.¨uÓ5ˆØ#1Ñ ˆ�[ð —N‘N ;°Ó7ˆ	ô �]‰]‹_ñ 	=Ø—|‘|×3Ñ3°E¸4×;LÑ;LÈd×N^ÑN^Ó_ˆHØ!Ÿ\™\¨(¯/©/Ó*;Ó<ˆN÷	=ð
 ×Ñ Ò&Ü—]‘] ;°×1AÑ1AÑ#AÀrÔJˆFÜ—]‘] >°D×4DÑ4DÑ#DÈ"ÔMˆFÜŸ8™8 F¨F¸kÐVZÔ[Ð_c×_oÑ_oÐstÑ_tÑu‰Là)×0Ñ0°RÐ0Ó8ˆLÜŸ?™?¨;¸ÓEˆLà×*Ñ*¨YÑ6¸×9QÑ9QÐT`Ñ9`Ñ`ˆ
ð Ø!Ø"Ø(ñ	
ð 	
÷	=ð 	=ús   ½AE%Å%E.)	NNrc   NNre   NNT)NrM   )r-   rO   rP   rQ   r)   r*   r   r%   r   r   Úfloatr2   r   r   Úboolr#   Úlistrt   rA   rS   r   rF   rT   rU   s   @r:   rW   rW   …   sh  ø„ ñ+ðb .2Ø59Ø &Ø37Ø04Ø!$Ø-1Ø+/Ø ñgàŸ9™9ðgð !  b§i¡iÐ1IÐ!IÑJðgð   §	¡	Ñ*ð	gð
 &.¨c¡]ðgð ðgð "*¨%¡ðgð ' u™oðgð ðgð ˜UŸ\™\Ñ*ðgð ˜EŸK™KÑ(ðgð õgðV *.ñà  ™ðð 
!ó	ð6 &Ø"&ñ%àð%ð ˜3‘-ð%ð
 
�‰ó%ð.
à—<‘<ð.
ð —L‘Lð.
ð 
ˆc�5—<‘<ÐÑ	 ÷	.
r;   rW   )rQ   ÚloggingÚtypingr   r   r   r2   Útorch.nnr)   Útorch.nn.functionalÚ
functionalr„   Útimm.modelsr   Ú
timm.utilsr   Útaskr	   Ú	getLoggerr-   r&   r*   r   rW   r!   r;   r:   ú<module>rž      s[   ðÙ PÛ ß (Ñ (ã Ý ß Ð å $Ý #å à
ˆ'×
Ñ
˜HÓ
%€ôqQ˜rŸy™yô qQôhk
˜Lõ k
r;   