§
    ­¸j=  ã                  ó^   — d Z ddlmZ ddlmZ ddlZddlmZ dd„Zdd„Zdd„Z	dd„Z
dd„ZdS )aü  Batched linear assignment solver for :class:`~rfdetr.models.matcher.HungarianMatcher`.

Wraps ``torch_linear_assignment`` behind a narrow, matcher-shaped API: fold every problem across
every decoder/aux/enc layer of one training step into a single batched call, then hand back only
the small integer index pairs. See ``.plans/active/plan-native-linear-assignment.md`` Phase M3
Item 2 for the measurement evidence and design rationale.

Two properties of the dependency drive the design, both measured on an L4 at RF-DETR shapes
(``bench_gpu_solver.py``, ``group_width=300``, targets 1-30):

* **The win scales with the batched problem count, not the problem size.** 52 problems measured
  1.15-1.37x SciPy (and 0.89-0.93x at 15-30 targets); 208 measured 2.0-2.5x; 624 measured ~5.9x.
  Splitting a step's problems across several calls therefore costs real throughput, so every
  problem in a step is padded to a common target count and solved in one call.
* **The convenience wrapper has data-dependent device operations.** ``assignment_to_indices``
  reads a CUDA bool in an ``if``, calls ``.item()``, and runs ``nonzero``/``masked_select``.
  Those operations can stall the host. Since the match count is known analytically, this module
  converts assignments to index pairs with shape-static ops and transfers both index tensors
  together.

Retained benchmarks characterize elapsed time but do not preserve a per-operation trace that
proves a synchronization count. This module therefore makes no exact synchronization claim; the
call structure keeps a whole step together because the solver's throughput depends on its batch
size.

Backend selection is deliberately *not* re-implemented here: the dependency owns that policy (its
Triton CUDA kernel on Linux NVIDIA compute capability >= 8.0 with Torch >= 2.4, SciPy on everything
else) and falls back internally, so this module is device-agnostic and its results are identical
everywhere.

``torch_linear_assignment`` ships in the ``train`` extra, and it is imported inside the solve
helper rather than at module scope: ``rfdetr.models`` imports ``criterion`` -> ``matcher`` -> this
module, so a module-scope import would make a plain ``import rfdetr`` fail on an inference-only
install that has no reason to solve an assignment problem at all.
é    )Úannotations)ÚdefaultdictN)ÚTensorÚstackedr   Únum_matchesÚintÚreturnútuple[Tensor, Tensor]c                ób  — ddl }|                     | ¦  «        }|dk    }t          j        |                     t          j        ¦  «        ddd¬¦  «        }|dd…d|…f         }|                     d|¦  «        }t          j        ||f¦  «                             ¦   «         }|d         |d         fS )aÛ  Solve a uniform batch of problems and return host-side index pairs.

    Converts the solver's per-row assignment into ``(rows, cols)`` with shape-static operations:
    ``num_matches`` is known by construction, and a stable descending sort of the matched mask
    lists the matched rows in ascending order. The two index tensors transfer together. This helper
    does not claim whether that transfer, ``nonzero``, or solver internals synchronize because no
    per-operation trace is retained.

    Args:
        stacked: ``[num_problems, group_width, targets]`` costs, all problems the same shape.
        num_matches: Matches per problem, ``min(group_width, targets)``.

    Returns:
        ``(rows, cols)``, each a host ``[num_problems, num_matches]`` int64 tensor.

    Examples:
        >>> import torch
        >>> rows, cols = _solve_to_indices(torch.arange(4, dtype=torch.float32).reshape(1, 2, 2), 2)
        >>> rows.tolist(), cols.tolist()
        ([[0, 1]], [[0, 1]])
    r   Né   T)ÚdimÚ
descendingÚstable)	Útorch_linear_assignmentÚbatch_linear_assignmentÚtorchÚargsortÚtoÚint8ÚgatherÚstackÚcpu)	r   r   r   Ú
assignmentÚmatchedÚorderÚrowsÚcolsÚpairs	            úi/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/rfdetr/models/_assignment.pyÚ_solve_to_indicesr    2   s°   € ð0 #Ð"Ð"Ð"à(×@Ò@ÀÑIÔI€JØ˜AŠo€GåŒM˜'Ÿ*š*¥U¤ZÑ0Ô0°aÀDÐQUÐVÑVÔV€EØ����L�[�L�Ô!€DØ×Ò˜Q Ñ%Ô%€DåŒ;˜˜d�|Ñ$Ô$×(Ò(Ñ*Ô*€DØ�Œ7�D˜”GÐÐó    Úcost_matricesúlist[Tensor]Úsizesú	list[int]Úgroup_widthÚ
group_detrÚmax_sizec           
     óÊ  — dg}|D ] }|                      |d         |z   ¦  «         Œ!| d                              t          | ¦  «        t          |¦  «        |||¦  «        }t          | ¦  «        D ]^\  }}	t          |¦  «        D ]I\  }
}|rB|	dd…||
         ||
         |z   …f         }|                     |||¦  «        |||
dd…dd…d|…f<   ŒJŒ_|                     d||¦  «        S )aq  Fold every ``(layer, image, group)`` problem into one uniformly shaped batch.

    Each image's target block is padded from its real count to ``max_size`` with a constant zero
    cost. Because ``group_width`` far exceeds ``max_size``, every feasible solution assigns all
    ``max_size`` columns exactly once, so a constant pad contributes the same amount to every
    arrangement and cannot change which assignment is optimal. Padded columns are discarded by the
    caller once the indices are back on the host.

    Args:
        cost_matrices: One ``[num_queries, sum(sizes)]`` compact cost matrix per layer.
        sizes: Each image's real target count, in batch order.
        group_width: Queries per group, shared by every layer here.
        group_detr: Number of query groups.
        max_size: Padded target count, ``max(sizes)``.

    Returns:
        ``[len(cost_matrices) * len(sizes) * group_detr, group_width, max_size]``, ordered
        layer-major, then image, then group.

    Examples:
        >>> import torch
        >>> _stack_padded([torch.ones(2, 3)], [1, 2], 2, 1, 2).shape
        torch.Size([2, 2, 2])
    r   éÿÿÿÿN)ÚappendÚ	new_zerosÚlenÚ	enumerateÚviewÚreshape)r"   r$   r&   r'   r(   ÚoffsetsÚsizer   Úlayer_indexÚcost_matrixÚimage_indexÚblocks               r   Ú_stack_paddedr7   W   s)  € ð> ˆc€GØð +ð +ˆØ�Š�w˜r”{ TÑ)Ñ*Ô*Ð*Ð*ð
 ˜AÔ×(Ò(­¨]Ñ);Ô);½SÀ¹Z¼ZÈÐU`ÐbjÑkÔk€GÝ$-¨mÑ$<Ô$<ð kð kÑ ˆ�[Ý!*¨5Ñ!1Ô!1ð 	kð 	kÑˆK˜Øð kØ# A A A w¨{Ô';¸gÀkÔ>RÐUYÑ>YÐ'YÐ$YÔZ�ØAFÇÂÈJÐXcÐeiÑAjÔAj�˜ [°!°!°!°Q°Q°Q¸¸¸Ð=Ñ>øð	kð �?Š?˜2˜{¨HÑ5Ô5Ð5r!   ú!list[list[tuple[Tensor, Tensor]]]c                óÈ  ‡‡‡‡— t          ‰¦  «        }t          | ‰|‰|¦  «        }t          |t          ||¦  «        ¦  «        \  }}t	          j        ‰|j        ¬¦  «                             ‰¦  «                             t          | ¦  «        ¦  «        }|| 
                    d¦  «        k     }	t	          j        |j        d         |j        ¬¦  «        ‰z  |z  }
||
 
                    d¦  «        z   |	         }||	         }ˆˆfd„| D ¦   «         }t	          j        ||¦  «        Št	          j        ||¦  «        Šˆˆˆfd„t          t          | ¦  «        ¦  «        D ¦   «         S )a£  Solve every layer in one batched call, then drop the padded columns on the host.

    Args:
        cost_matrices: One compact cost matrix per layer, all sharing ``group_width``.
        sizes: Each image's real target count, in batch order.
        group_width: Queries per group.
        group_detr: Number of query groups.

    Returns:
        One list per layer of per-image ``(row_indices, col_indices)`` CPU int64 tensor pairs.

    Examples:
        >>> import torch
        >>> costs = [torch.arange(8, dtype=torch.float32).reshape(4, 2)]
        >>> [(r.tolist(), c.tolist()) for r, c in _assign_padded(costs, [1, 1], 4, 1)[0]]
        [([0], [0]), ([0], [0])]
    ©Údtyper   r   c                ó$   •— g | ]}‰D ]}‰|z  ‘ŒŒS © r=   )Ú.0Ú_r2   r'   r$   s      €€r   ú
<listcomp>z"_assign_padded.<locals>.<listcomp>¬   s+   ø€ ÐLÐLÐL qÀeÐLÐL¸d�˜dÑ"ÐLÐLÐLÐLr!   c                óh   •‡— g | ]-Šˆˆˆˆfd „t          t          ‰¦  «        ¦  «        D ¦   «         ‘Œ.S )c                ó|   •— g | ]8}‰‰t          ‰¦  «        z  |z            ‰‰t          ‰¦  «        z  |z            f‘Œ9S r=   )r-   )r>   r5   Ú
col_chunksr3   Ú
row_chunksr$   s     €€€€r   r@   z-_assign_padded.<locals>.<listcomp>.<listcomp>°   s]   ø€ ð 	
ð 	
ð 	
àð ˜¥c¨%¡j¤jÑ0°;Ñ>Ô?ÀÈKÕZ]Ð^cÑZdÔZdÑLdÐgrÑLrÔAsÐtð	
ð 	
ð 	
r!   )Úranger-   )r>   r3   rC   rD   r$   s    @€€€r   r@   z"_assign_padded.<locals>.<listcomp>¯   sj   øø€ ð ð ð ð
 ð		
ð 	
ð 	
ð 	
ð 	
ð 	
ð 	
å$¥S¨¡Z¤ZÑ0Ô0ð	
ñ 	
ô 	
ðð ð r!   )Úmaxr7   r    Úminr   Útensorr;   Úrepeat_interleaveÚrepeatr-   Ú	unsqueezeÚarangeÚshapeÚsplitrE   )r"   r$   r&   r'   r(   r   r   r   Úsize_per_problemÚkeepÚgroup_offsetÚ	kept_rowsÚ	kept_colsÚ	per_imagerC   rD   s    ` `          @@r   Ú_assign_paddedrU   †   sq  øøøø€ õ. �5‰zŒz€HÝ˜M¨5°+¸zÈ8ÑTÔT€GÝ" 7­C°¸XÑ,FÔ,FÑGÔG�J€Dˆ$õ ”| E°´Ð<Ñ<Ô<×NÒNÈzÑZÔZ×aÒaÕbeÐfsÑbtÔbtÑuÔuÐàÐ"×,Ò,¨QÑ/Ô/Ò/€DÝ”< ¤
¨1¤°T´ZÐ@Ñ@Ô@À:ÑMÐP[Ñ[€Lð ˜×.Ò.¨qÑ1Ô1Ñ1°4Ô8€IØ�T”
€IàLÐLÐLÐLÐL¨MÐLÑLÔL€IÝ”˜Y¨	Ñ2Ô2€JÝ”˜Y¨	Ñ2Ô2€Jðð ð ð ð ð õ
 !¥ ]Ñ!3Ô!3Ñ4Ô4ðñ ô ð r!   Úgroup_widthsc           	     óX  ‡ ‡‡‡‡‡— dgŠ‰D ] Š‰                      ‰d         ‰z   ¦  «         Œ!t          t          ¦  «        }t          ‰¦  «        D ]L\  }Št          |¦  «        D ]7\  }Št	          ‰¦  «        D ]"}|‰‰f                               |||f¦  «         Œ#Œ8ŒMˆˆfd„t	          t          ‰ ¦  «        ¦  «        D ¦   «         }|                     ¦   «         D ]€\  \  ŠŠ}	t          j        ˆ ˆˆˆfd„|	D ¦   «         ¦  «        }
t          |
t          ‰‰¦  «        ¦  «        \  }}t          |	¦  «        D ]$\  }\  }}}||         ||         f|||f         |<   Œ%Œ�g }t          |¦  «        D ]½\  }Šg }t	          t          ‰¦  «        ¦  «        D ]„}|||f         d         \  }}t	          d‰¦  «        D ]G}|||f         |         \  }}t          j        ||‰|z  z   g¦  «        }t          j        ||g¦  «        }ŒH|                      ||f¦  «         Œ…|                      |¦  «         Œ¾|S )a›  Solve one batched call per distinct problem shape.

    The fallback for the two cases padding cannot serve: layers whose query counts differ, and
    target counts at or above ``group_width``, where ``min(group_width, targets)`` stops being the
    real target count and padded columns would no longer be separable from real ones.

    Args:
        cost_matrices: One compact cost matrix per layer.
        sizes: Each image's real target count, in batch order.
        group_widths: Each layer's queries per group.
        group_detr: Number of query groups.

    Returns:
        One list per layer of per-image ``(row_indices, col_indices)`` CPU int64 tensor pairs.

    Examples:
        >>> import torch
        >>> costs = [torch.arange(8, dtype=torch.float32).reshape(4, 2)]
        >>> [(r.tolist(), c.tolist()) for r, c in _assign_bucketed_by_size(costs, [1, 1], [4], 1)[0]]
        [([0], [0]), ([0], [0])]
    r   r*   c                ó¬   •— i | ]P}t          t          ‰¦  «        ¦  «        D ]1}||ft          j        d ¦  «        t          j        d ¦  «        fg‰z  “Œ2ŒQS )r   )rE   r-   r   Úempty)r>   r3   r5   r'   r$   s      €€r   ú
<dictcomp>z,_assign_bucketed_by_size.<locals>.<dictcomp>Ý   s{   ø€ ð Kð Kð KàÝ ¥ U¡¤Ñ,Ô,ðKð Kð ð 
�kÐ"¥e¤k°!¡n¤nµe´kÀ!±n´nÐ%EÐ$FÈÑ$SðKð Kð Kð Kr!   c                óp   •— g | ]2\  }}}‰|         |‰z  |d z   ‰z  …‰|         ‰|         ‰z   …f         ‘Œ3S )r   r=   )r>   r3   Úgroup_indexr5   r"   r&   r1   r2   s       €€€€r   r@   z,_assign_bucketed_by_size.<locals>.<listcomp>ä   sn   ø€ ð ð ð ñ
 :�K ¨kð	 ˜kÔ*Ø +Ñ-°¸q±ÀKÑ0OÐOØ˜KÔ(¨7°;Ô+?À$Ñ+FÐFðHôðð ð r!   r   )r+   r   Úlistr.   rE   r-   Úitemsr   r   r    rG   Úcat)r"   r$   rV   r'   Úbucketsr5   r3   r\   Úper_group_pairsÚproblemsr   r   r   Úproblem_indexÚresultsÚlayer_resultÚ	next_rowsÚ	next_colsr&   r1   r2   s   `` `              @@@r   Ú_assign_bucketed_by_sizerh   ¸   só  øøøøøø€ ð6 ˆc€GØð +ð +ˆØ�Š�w˜r”{ TÑ)Ñ*Ô*Ð*Ð*åALÍTÑARÔAR€GÝ& uÑ-Ô-ð ]ð ]Ñˆ�TÝ(1°,Ñ(?Ô(?ð 	]ð 	]Ñ$ˆK˜Ý$ ZÑ0Ô0ð ]ð ]�Ø˜ dÐ+Ô,×3Ò3°[À+È{Ð4[Ñ\Ô\Ð\Ð\ð]ð	]ðKð Kð Kð Kð Kå ¥ ]Ñ!3Ô!3Ñ4Ô4ðKñ Kô K€Oð
 *1¯ª©¬ð rð rÑ%Ñˆ�d˜XÝ”+ðð ð ð ð ð ð ð
 >Fðñ ô ñ
ô 
ˆõ ' wµ°KÀÑ0FÔ0FÑGÔG‰
ˆˆdÝFOÐPXÑFYÔFYð 	rð 	rÑBˆMÑB˜K¨°kØHLÈ]ÔH[Ð]aÐboÔ]pÐGqˆO˜[¨+Ð6Ô7¸ÑDÐDð	rð 24€GÝ$-¨lÑ$;Ô$;ð 	%ð 	%Ñ ˆ�[Ø46ˆÝ ¥ U¡¤Ñ,Ô,ð 	.ð 	.ˆKØ(¨+°{Ð)CÔDÀQÔG‰JˆD�$Ý$ Q¨
Ñ3Ô3ð 4ð 4�Ø'6¸À[Ð7QÔ'RÐS^Ô'_Ñ$�	˜9Ý”y $¨	°KÀ+Ñ4MÑ(MÐ!NÑOÔO�Ý”y $¨	Ð!2Ñ3Ô3��Ø×Ò  t Ñ-Ô-Ð-Ð-Ø�Š�|Ñ$Ô$Ð$Ð$Ø€Nr!   c                ó  ‡‡— g }| D ]F}|j         d         }||z  dk    rt          d|› d|› d�¦  «        ‚|                     ||z  ¦  «         ŒG| d         j        sd„ | D ¦   «         } t	          ‰¦  «        }|dk    r/t          j        dt
          j        ¬¦  «        Šˆˆfd„| D ¦   «         S t          t          |¦  «        ¦  «        dk    r$||d         k    rt          | ‰|d         |¦  «        S t          | ‰||¦  «        S )	a  Solve every layer's compact cost matrix with as few batched device calls as possible.

    Folds every ``(layer, group, image)`` problem of one training step into a single call by
    padding to a common target count, since the solver's advantage grows steeply with the batched
    problem count. Callers are expected to route only CUDA work here; off CUDA the dependency
    resolves to the same SciPy solve behind extra bookkeeping. See the plan doc's M3 Item 2 notes.

    Examples:
        >>> import torch
        >>> costs = [torch.arange(8, dtype=torch.float32).reshape(4, 2)]
        >>> [(rows.tolist(), cols.tolist()) for rows, cols in assign_many_bucketed(costs, [1, 1], 1)[0]]
        [([0], [0]), ([0], [0])]

    Args:
        cost_matrices: One ``[num_queries, sum(sizes)]`` compact cost matrix per layer, all on the
            same device with the same dtype, as built by
            ``HungarianMatcher._compute_compact_detection_cost_matrix`` /
            ``_compute_stacked_compact_cost_matrices``. Any device is accepted; a non-CUDA
            accelerator tensor is moved to the host first (see below).
        sizes: Each image's real (unpadded) target count, in batch order, shared by every layer.
        group_detr: Number of query groups; ``num_queries`` must be evenly divisible by it.

    Returns:
        One list per layer (``cost_matrices`` order) of per-image ``(row_indices, col_indices)``
        CPU int64 tensor pairs, group-concatenated exactly like
        ``HungarianMatcher._assign_compact_cost_matrix``.

    Raises:
        ValueError: If ``num_queries`` is not evenly divisible by ``group_detr``.
        ModuleNotFoundError: If ``torch_linear_assignment`` is missing, which means an install
            without the ``train`` extra reached a training-only code path.
    r   znum_queries (z#) must be divisible by group_detr (ú)c                ó6   — g | ]}|                      ¦   «         ‘ŒS r=   )r   )r>   r4   s     r   r@   z(assign_many_bucketed.<locals>.<listcomp>1  s"   € ÐLÐLÐL¨{˜ŸšÑ*Ô*ÐLÐLÐLr!   r:   c                ó,   •— g | ]}ˆfd „‰D ¦   «         ‘ŒS )c                ó   •— g | ]}‰‰f‘ŒS r=   r=   )r>   r?   rY   s     €r   r@   z3assign_many_bucketed.<locals>.<listcomp>.<listcomp>6  s   ø€ Ð/Ð/Ð/ A�%˜�Ð/Ð/Ð/r!   r=   )r>   r?   rY   r$   s     €€r   r@   z(assign_many_bucketed.<locals>.<listcomp>6  s.   ø€ ÐGÐGÐG°AÐ/Ð/Ð/Ð/¨Ð/Ñ/Ô/ÐGÐGÐGr!   r   )rM   Ú
ValueErrorr+   Úis_cudarF   r   rY   Úint64r-   ÚsetrU   rh   )r"   r$   r'   rV   r4   Únum_queriesr(   rY   s    `     @r   Úassign_many_bucketedrs   þ   s;  øø€ ðN !€LØ$ð 7ð 7ˆØ!Ô'¨Ô*ˆØ˜Ñ# qÒ(Ð(ÝÐj¨[ÐjÐjÐ]gÐjÐjÐjÑkÔkÐkØ×Ò˜K¨:Ñ5Ñ6Ô6Ð6Ð6ð ˜ÔÔ#ð MØLÐL¸mÐLÑLÔLˆå�5‰zŒz€HØ�1‚}€}Ý”˜A¥U¤[Ð1Ñ1Ô1ˆØGÐGÐGÐGÐG¸ÐGÑGÔGÐGõ �3ˆ|ÑÔÑÔ Ò"Ð" x°<À´?Ò'BÐ'BÝ˜m¨U°LÀ´OÀZÑPÔPÐPÝ# M°5¸,È
ÑSÔSÐSr!   )r   r   r   r   r	   r
   )r"   r#   r$   r%   r&   r   r'   r   r(   r   r	   r   )
r"   r#   r$   r%   r&   r   r'   r   r	   r8   )
r"   r#   r$   r%   rV   r%   r'   r   r	   r8   )r"   r#   r$   r%   r'   r   r	   r8   )Ú__doc__Ú
__future__r   Úcollectionsr   r   r   r    r7   rU   rh   rs   r=   r!   r   ú<module>rw      sÍ   ðð"ð "ðH #Ð "Ð "Ð "Ð "Ð "à #Ð #Ð #Ð #Ð #Ð #à €€€Ø Ð Ð Ð Ð Ð ð"ð "ð "ð "ðJ,6ð ,6ð ,6ð ,6ð^/ð /ð /ð /ðdCð Cð Cð CðL>Tð >Tð >Tð >Tð >Tð >Tr!   