
    ^jX`                        d Z ddlZddlmZ ddlZddlmZ ddlmZm	Z	m
Z
 ddlmZ ddlmZmZmZmZ ddlmZ 	 dd	lmZ dd
lmZmZmZ ddlmZmZmZm Z  ddl!m"Z" ddl#m$Z$  e$       Z%ddZ&e G d de      Z'ndZ' G d de      Z(de)de*fdZ+de)dz  de*fdZ,d de-e)z  de)dz  de*fdZ.dddedede)dz  dedef
dZ/y# e$ r dZY w xY w)!uA   Trainer factory — assembles a PTL Trainer from RF-DETR configs.    N)Any)Trainer)ModelCheckpointRichProgressBarTQDMProgressBar)RichProgressBarTheme)	CSVLoggerMLFlowLoggerTensorBoardLoggerWandbLogger)DDPStrategy)_MultiProcessingLauncher)KeypointTrainConfigModelConfigTrainConfig)BestModelCallbackDropPathCallbackRFDETREarlyStoppingRFDETREMACallback)COCOEvalCallback)
get_loggerreturnc                      ddl m}  y)a  Probe the full tensorboard import chain to surface numpy/tensorflow incompatibilities early.

    When tensorboard is installed alongside a numpy-2.0-incompatible tensorflow, importing
    ``torch.utils.tensorboard`` raises ``AttributeError`` at module level (e.g. ``np.float_`` was
    removed in NumPy 2.0).  Calling this function inside the logger-construction try/except lets
    ``build_trainer`` degrade gracefully to CSV-only logging instead of crashing mid-training.

    Raises:
        ImportError: If the ``tensorboard`` package is absent.
        AttributeError: If ``torch.utils.tensorboard`` fails to import due to a NumPy 2.0 /
            tensorflow incompatibility.
    r   SummaryWriterN)torch.utils.tensorboardr   r   s    b/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/rfdetr/training/trainer.py&_try_import_tensorboard_summary_writerr   '   s     6    c                   &    e Zd ZdZedefd       Zy)_InteractiveSpawnLauncherz=Spawn launcher that reports itself as interactive-compatible.r   c                      y)NT selfs    r   is_interactive_compatiblez3_InteractiveSpawnLauncher.is_interactive_compatibleO   s    r   N)__name__
__module____qualname____doc__propertyboolr&   r#   r   r   r!   r!   L   s    K		t 	 
	r   r!   c                       e Zd ZdZddZy)_NotebookSpawnDDPStrategyzFSpawn-based DDP strategy that works inside Jupyter / Kaggle notebooks.Nc                     | j                   t        d      t        t        d      t        | | j                        | _        y )Nzs_NotebookSpawnDDPStrategy requires a cluster environment; ensure the strategy is initialised through PTL's Trainer.zNotebook spawn strategy requires pytorch_lightning.strategies.launchers.multiprocessing._MultiProcessingLauncher. Your installed PyTorch Lightning version changed this private API; pin/upgrade PTL to a compatible version in the supported >=2.6,<3 range.)start_method)cluster_environmentRuntimeErrorr!   _start_method	_launcherr$   s    r   _configure_launcherz-_NotebookSpawnDDPStrategy._configure_launcherZ   sR    ##+L  %,[  34dFXFXYr   r   N)r'   r(   r)   r*   r5   r#   r   r   r.   r.   W   s    PZr   r.   strategyc                 L    | j                         t        fddD              S )zLReturn whether a TrainConfig strategy string requests distributed execution.c              3   &   K   | ]  }|v  
 y wNr#   ).0tokenstrategy_names     r   	<genexpr>z5_is_distributed_strategy_requested.<locals>.<genexpr>m   s     P%u%Ps   )ddpfsdp	deepspeed)lowerany)r7   r=   s    @r   "_is_distributed_strategy_requestedrD   j   s!    NN$MP3OPPPr   acceleratorc                     | xs dj                         j                         }|dv rAt        j                  j	                         xr! t        j                  j                         dkD  S y)zJReturn whether PTL auto/all device resolution can select multiple devices.auto)rG   cudagpu   F)striprB   torchrH   is_availabledevice_count)rE   accelerator_names     r   &_accelerator_has_multiple_auto_devicesrP   p   sU    #-v446<<>22zz&&(JUZZ-D-D-F-JJr   devicesc                 n   t        | t              r| dk(  rt        |      S | dkD  S | j                         j	                         }|dv rt        |      S |j                         rt        |      dkD  S d|v r<t        |j                  d      D cg c]  }|j                         s| c}      dkD  S yc c}w )zQReturn whether the configured devices value explicitly requests multiple devices.rJ   )rG   z-1,F)
isinstanceintrP   rK   rB   isdigitlensplit)rQ   rE   devices_nameentrys       r   _requests_multiple_devicesr\   x   s    '3b=9+FF{==?((*L~%5kBB< 1$$
l|'9'9#'>Pe%++-EPQTUUU Qs   B2#B2)rE   train_configmodel_configtrainer_kwargsc                   | j                   dt        ffd}|j                  dj                        |j                  dj                        }|j                  dj
                        }t        t              rj                         j                         nd}t        j                        }t        t              |k7  r*t        dt        t               dj                   d	      t        t                    xs |d
kD  xs t        |      }	|r|	rt        dd|d|d      |dv r$t!        dd      t"        j%                  d|       nH|dk(  s|dk(  r>|	r<t'        d      |dk(  rt"        j%                  d       nt"        j%                  d       t)        fddD              }
t        j*                        xr |
 }j*                  r"|
r t-        j.                  ddt0        d       g }j2                  dk(  r'|j5                  t7        d t9        d!"      #             n*j2                  d$k(  r|j5                  t;        d %             |r;|j5                  t=        j>                  j@                  jB                  &             jD                  d'kD  r%|j5                  tG        jD                  (             |j5                  tI        jJ                  jL                  jN                  jP                  jR                  )             jT                  d
k7  r+|j5                  tW        jX                  d*d
d
d+d+d+,             |j5                  tW        jX                  d-jT                  d.d+d+d+,             |rd/}d0}njL                  rd1}d2}nd3}d4}|r|nd}jZ                  }|j5                  t]        jX                  ||j^                  j`                  |5             jb                  rH|j5                  te        jf                  jh                  jj                  ||j`                  6             tm        jX                  d7d78      g}jn                  r2	 tq                |j5                  ts        jX                  d7d78             jz                  r<	 |j5                  t}        j~                  j                  jX                  :             j                  r@	 |j5                  t        j                  xs d<j~                  jX                  =             j                  rt        d?      j                  }j                  }|}|rd
}d}nj                  }|}j                  j                  j
                   |       |||||r|nd+j2                  dujX                  d@d+dA}|j                  |       |d<   |rWdBD ]H  }||v s|dCk(  rdDndE}|dCk(  rdFndG}t-        j.                  dH|dI||   dJ| dK| dL| dMt0        d       J d
|dC<   d|dN<   t        dOi |S # tt        tv        f$ r!}t"        jy                  d9|       Y d}~d}~ww xY w# t        $ r!}t"        jy                  d;|       Y d}~d}~ww xY w# t        $ r!}t"        jy                  d>|       Y d}~d}~ww xY w)Paj  Assemble a PTL ``Trainer`` with the full RF-DETR callback and logger stack.

    Resolves training precision from ``model_config.amp`` and device capability, guards EMA against sharded strategies,
    wires conditional loggers, and applies promoted training knobs (sync_batchnorm, strategy).

    Args:
        train_config: Training hyperparameter configuration.
        model_config: Architecture configuration. Used for precision resolution
            (``model_config.amp``) and to guard against unsupported distributed
            configurations for keypoint models.
        accelerator: PTL accelerator string (e.g. ``"auto"``, ``"cpu"``, ``"gpu"``).
            Defaults to ``None`` which reads from ``train_config.accelerator`` (itself defaulting to ``"auto"``). Pass
            ``"cpu"`` to override auto-detection (e.g. when the caller explicitly requests CPU training via
            ``device="cpu"``).
        **trainer_kwargs: Extra keyword arguments forwarded to ``pytorch_lightning.Trainer``. Use this to pass
            PTL-native flags that are not exposed through ``TrainConfig``, for example::

                build_trainer(tc, mc, fast_dev_run=2)

            Most keys present in both ``trainer_kwargs`` and the built config dict are overridden by the value in
            ``trainer_kwargs``. Detection and segmentation models forward ``accumulate_grad_batches`` from
            ``train_config.grad_accum_steps`` and ``gradient_clip_val`` from ``train_config.clip_max_norm`` to the
            Trainer normally. Keypoint models force ``accumulate_grad_batches=1`` and ``gradient_clip_val=None``
            because ``RFDETRModelModule`` owns both operations under manual optimization; passing those keys for a
            keypoint config raises a ``UserWarning`` to make the override explicit.

    Returns:
        A configured ``pytorch_lightning.Trainer`` instance.
    Nr   c                     j                   s:j                  dk7  r*t        j                  dj                  dt        d       ydk(  ryj                  } t
        j                  j                         r~| dk(  ry	| d
k(  rQt
        j                  j                         ryt        j                  d       t        j                  dt        d       y	t
        j                  j                         rdS d	S t
        j                  j                  j                         r7| d
k(  r1t        j                  d       t        j                  dt        d       y	y)NrG   z
amp_dtype=z+ has no effect when model_config.amp=False.   
stacklevelz32-truecpufp16z16-mixedbf16z
bf16-mixedzqamp_dtype='bf16' was requested but this CUDA device does not support bfloat16; falling back to fp16 ('16-mixed').zXamp_dtype='bf16' is not applied on MPS; RF-DETR uses fp16 ('16-mixed') for MPS autocast.)amp	amp_dtypewarningswarnUserWarningrL   rH   rM   is_bf16_supported_loggerwarningbackendsmps)ri   rE   r^   tcs    r   _resolve_precisionz)build_trainer.<locals>._resolve_precision   s&   ||v%  00[\ 
  % LL	 ::""$F"!F":://1'9 9 	 "#(::#?#?#A<QzQ>>**,F"n n 
 r   r7   rQ   	num_nodesz;Config/model mismatch: isinstance(tc, KeypointTrainConfig)=z* but model_config.use_grouppose_keypoints=zT. Pass KeypointTrainConfig for keypoint models and TrainConfig for detection models.rJ   zMKeypoint training currently does not support distributed execution (strategy=z
, devices=z, num_nodes=z]). Use single-process training for now (for example strategy='auto', devices=1, num_nodes=1).)ddp_notebook	ddp_spawnspawnT)r0   find_unused_parametersuI   %s → spawn-based DDP to avoid OpenMP thread pool corruption after fork.r?   rG   )rx   uX   strategy='auto' with distributed execution → DDPStrategy(find_unused_parameters=True).u<   strategy='ddp' → DDPStrategy(find_unused_parameters=True).c              3   T   K   | ]  }|t              j                         v  ! y wr:   )strrB   )r;   sr7   s     r   r>   z build_trainer.<locals>.<genexpr>*  s#     L!s8}**,,Ls   %()r@   rA   zTEMA disabled: RFDETREMACallback is not compatible with sharded strategies (strategy=z.). Set use_ema=False to suppress this warning.rb   rc   rich   z.3e)metrics_format)refresh_ratethemetqdm)r   )decaytauupdate_interval_stepsg        )	drop_path)max_detssegmentationeval_intervallog_per_class_metricskeypoint_oks_sigmaslastF)dirpathfilenameevery_n_epochs
save_top_kenable_version_counterauto_insert_metric_nameverbosezcheckpoint_{epoch}rS   zval/keypoint_map_50_95zval/ema_keypoint_map_50_95zval/segm_mAP_50_95zval/ema_segm_mAP_50_95zval/mAP_50_95zval/ema_mAP_50_95)
output_dirmonitor_regularmonitor_emarun_testskip_best_epochssmooth_alpha)patience	min_deltause_emar   r   r    )save_dirnameversionzTensorBoard logging disabled: %s. If using NumPy 2.x, ensure your TensorBoard installation is NumPy 2.0 compatible (the failure can originate from tensorboard.compat.tensorflow_stub). Install TensorBoard with: pip install tensorboard)r   projectr   z;WandB logging disabled: %s. Install with: pip install wandbrfdetr)experiment_namerun_namer   z=MLflow logging disabled: %s. Install with: pip install mlflowzKClearML logging is not yet supported. Remove clearml=True from TrainConfig.2   )
max_epochsrE   rQ   rt   r7   	precisionaccumulate_grad_batchesgradient_clip_valsync_batchnorm	callbacksloggerenable_progress_bardefault_root_dirlog_every_n_stepsdeterministic)r   r   r   1Nonegrad_accum_stepsclip_max_normz'build_trainer() ignored trainer_kwargs[z]=z1 for a keypoint model. The model will train with =z regardless of the value passed here because RFDETRModelModule owns gradient accumulation and clipping under manual optimization. To change the effective value, set TrainConfig.z	 instead.r   r#   )KrE   rz   getr7   rQ   rt   rU   rK   rB   r,   use_grouppose_keypointsr   
ValueErrorrD   r\   NotImplementedErrorr.   rn   info_DDPStrategyrC   r   rj   rk   rl   progress_barappendr   r   r   r   	ema_decayema_tauema_update_intervalr   r   r   eval_max_detssegmentation_headr   r   r   checkpoint_intervalr   r   r   r   r   r   early_stoppingr   early_stopping_patienceearly_stopping_min_deltaearly_stopping_use_emar	   tensorboardr   r   ImportErrorAttributeErrorro   wandbr   runr   ModuleNotFoundErrormlflowr
   clearmlr   sync_bnr   epochsupdater   )r]   r^   rE   r_   rs   rQ   rt   r=   has_keypointsdistributed_requestedsharded
enable_emar   r   early_stopping_monitor_emar   best_model_smooth_alphaloggersexcr   r   manual_optimizationr   r   trainer_configkey	effectivealtr7   rr   s    ``                         @@r   build_trainerr      s   H 
Bnn? ?D !!*bkk:H  BJJ7G"";=I0:8S0IHNN$**,tM==>M")*m;I*UWYlJmIn o88D8\8\7] ^aa
 	
 	+3x=9 	<q=	<%g{; 
 . "!Jwki] Sii
 	
 55,'Z^_W	
 
%	MV$;@U  t<F"LLj LLN L6KLLGbjj!1'kJ	zzg!$RT		
 I	& *%@	
 
F	"a89llJJ&(&<&<	
 
||c)BLLAB %%%77**"$":": " 6 6	
 
" ',(-
	
 MM)11#($)	

 2%A"		'	'.%=")%8"0:,K oo }}+#[[000	
	 
335511 /6!#!4!4		
" BKLG	~~	24NN!]]  
xx		`NNJJ]] 
yy		bNN$&JJ$:(VV]] 
zz!"opp ++MJJG ('(*."$"5"5) ii"::\\')#:.!$'%!d:MM&N" .)!)N:
 D 	Cn$#&*C#CC	,/3L,L(Ra=cWB~VYGZF] ^88;uAi[ ITTWSXXac   		 5601 /3*+$^$$A ^, 	OOD  	$ # 	`OOY[^__	` # 	bOO[]`aa	bsH    1Y >;Z ?Z4 Z#Y??Z	Z1Z,,Z14	[=[[r6   r:   )0r*   rj   typingr   rL   pytorch_lightningr   pytorch_lightning.callbacksr   r   r   2pytorch_lightning.callbacks.progress.rich_progressr   pytorch_lightning.loggersr	   r
   r   r   pytorch_lightning.strategiesr   r   6pytorch_lightning.strategies.launchers.multiprocessingr   r   rfdetr.configr   r   r   rfdetr.training.callbacksr   r   r   r   #rfdetr.training.callbacks.coco_evalr   rfdetr.utilities.loggerr   rn   r   r!   r.   rz   r,   rD   rP   rV   r\   r   r#   r   r   <module>r      s/   H    % Y Y S ] ] D
$_ H G  A .
,6F '$<  !%Z Z&Q Q Qd
 t c	 d
 VZ ( #	J%J%J% t	J%
 J% J%c  $#$s   C C
C