+
    QV-jî_  ã                   ó¢  € ^ RI t ^ RIHt ^ RIHt ^ RIHtHtHt ^ RI	t
^ RIt^ RIHt ^ RIHt ^RIHt ^RIHt ^R	IHt ^R
IHtHt ^RIHtHt ]'       d   ^RIHt ]P:                  ! ]4      t] ! R R4      4       t  ! R R4      t! ! R R]4      t"] ! R R]4      4       t# ! R R]PH                  4      t% ! R R]4      t& ! R R4      t'R# )é    N)Ú	dataclass)Ú	lru_cache)ÚTYPE_CHECKINGÚAnyÚUnion)Únn)ÚBCELoss)Úinitialization)ÚPreTrainedConfig)ÚPreTrainedModel)ÚModelOutputÚlogging)Ú#SynthIDTextWatermarkLogitsProcessorÚWatermarkLogitsProcessor)ÚWatermarkingConfigc                   óL   a € ] tR t^&t o RtRtRtRtRtRt	Rt
RtV 3R ltRtV tR# )ÚWatermarkDetectorOutputaÉ  
Outputs of a watermark detector.

Args:
    num_tokens_scored (np.ndarray of shape (batch_size)):
        Array containing the number of tokens scored for each element in the batch.
    num_green_tokens (np.ndarray of shape (batch_size)):
        Array containing the number of green tokens for each element in the batch.
    green_fraction (np.ndarray of shape (batch_size)):
        Array containing the fraction of green tokens for each element in the batch.
    z_score (np.ndarray of shape (batch_size)):
        Array containing the z-score for each element in the batch. Z-score here shows
        how many standard deviations away is the green token count in the input text
        from the expected green token count for machine-generated text.
    p_value (np.ndarray of shape (batch_size)):
        Array containing the p-value for each batch obtained from z-scores.
    prediction (np.ndarray of shape (batch_size)), *optional*:
        Array containing boolean predictions whether a text is machine-generated for each element in the batch.
    confidence (np.ndarray of shape (batch_size)), *optional*:
        Array containing confidence scores of a text being machine-generated for each element in the batch.
Nc                ó\  <€ V ^8„  d   Qh/ S[ P                  R,          ;R&   S[ P                  R,          ;R&   S[ P                  R,          ;R&   S[ P                  R,          ;R&   S[ P                  R,          ;R&   S[ P                  R,          ;R&   S[ P                  R,          ;R&   # )	é   NÚnum_tokens_scoredÚnum_green_tokensÚgreen_fractionÚz_scoreÚp_valueÚ
predictionÚ
confidence©ÚnpÚndarray)ÚformatÚ__classdict__s   "€Úu/Volumes/fast/ai/experiments/ui-tars-smoke/.venv/lib/python3.14/site-packages/transformers/generation/watermarking.pyÚ__annotate__Ú$WatermarkDetectorOutput.__annotate__&   sŸ   ø‡ ‚ ñ0 —z‘z DÕ(Ñ/ñ1 ñ2 —j‘j 4Õ'Ñ.ñ3 ñ4 —J‘J Õ%Ñ,ñ5 ñ6 �Z‰Z˜$ÕÑ%ñ7 ñ8 �Z‰Z˜$ÕÑ%ñ9 ñ: —
‘
˜TÕ!Ñ(ñ; ñ< —
‘
˜TÕ!Ñ(ò= ó    © )Ú__name__Ú
__module__Ú__qualname__Ú__firstlineno__Ú__doc__r   r   r   r   r   r   r   Ú__annotate_func__Ú__static_attributes__Ú__classdictcell__©r!   s   @r"   r   r   &   s8   ø‡ € ñð, ,0ÐØ*.ÐØ(,€NØ!%€GØ!%€GØ$(€JØ$(€J÷= ƒ r%   r   c                   ó�   a € ] tR t^Gt o RtRV 3R lR lltV 3R lR ltV 3R lR ltV 3R lR	 ltRR
 lt	RV 3R lR llt
RtV tR# )ÚWatermarkDetectora»	  
Detector for detection of watermark generated text. The detector needs to be given the exact same settings that were
given during text generation to replicate the watermark greenlist generation and so detect the watermark. This includes
the correct device that was used during text generation, the correct watermarking arguments and the correct tokenizer vocab size.
The code was based on the [original repo](https://github.com/jwkirchenbauer/lm-watermarking/tree/main).

See [the paper](https://huggingface.co/papers/2306.04634) for more information.

Args:
    model_config (`PreTrainedConfig`):
        The model config that will be used to get model specific arguments used when generating.
    device (`str`):
        The device which was used during watermarked text generation.
    watermarking_config (Union[`WatermarkingConfig`, `Dict`]):
        The exact same watermarking config and arguments used when generating text.
    ignore_repeated_ngrams (`bool`, *optional*, defaults to `False`):
        Whether to count every unique ngram only once or not.
    max_cache_size (`int`, *optional*, defaults to 128):
        The max size to be used for LRU caching of seeding/sampling algorithms called for every token.

Examples:

```python
>>> from transformers import AutoTokenizer, AutoModelForCausalLM, WatermarkDetector, WatermarkingConfig

>>> model_id = "openai-community/gpt2"
>>> model = AutoModelForCausalLM.from_pretrained(model_id)
>>> tok = AutoTokenizer.from_pretrained(model_id)
>>> tok.pad_token_id = tok.eos_token_id
>>> tok.padding_side = "left"

>>> inputs = tok(["This is the beginning of a long story", "Alice and Bob are"], padding=True, return_tensors="pt")
>>> input_len = inputs["input_ids"].shape[-1]

>>> # first generate text with watermark and without
>>> watermarking_config = WatermarkingConfig(bias=2.5, seeding_scheme="selfhash")
>>> out_watermarked = model.generate(**inputs, watermarking_config=watermarking_config, do_sample=False, max_length=20)
>>> out = model.generate(**inputs, do_sample=False, max_length=20)

>>> # now we can instantiate the detector and check the generated text
>>> detector = WatermarkDetector(model_config=model.config, device="cpu", watermarking_config=watermarking_config)
>>> detection_out_watermarked = detector(out_watermarked, return_dict=True)
>>> detection_out = detector(out, return_dict=True)
>>> detection_out_watermarked.prediction
array([ True,  True])

>>> detection_out.prediction
array([False,  False])
```
c          
      óJ   <€ V ^8„  d   QhRRRS[ RS[RS[3,          RS[RS[/# )r   Úmodel_configr   ÚdeviceÚwatermarking_configr   Úignore_repeated_ngramsÚmax_cache_size)Ústrr   ÚdictÚboolÚint)r    r!   s   "€r"   r#   ÚWatermarkDetector.__annotate__{   sO   ø€ ÷ `ñ `à(ð`ñ ð`ñ #Ð#7¹Ð#=Õ>ð	`ñ
 !%ð`ñ ñ`r%   c                óV  € \        V\        4      '       g   VP                  4       pVP                  '       g   VP                  MVP
                  V n        VR ,          V n        W@n        \        RRVP                  RV/VB V n
        \        VR7      ! V P                  4      V n        R# )Úgreenlist_ratioÚ
vocab_sizer4   )ÚmaxsizeNr&   )Ú
isinstancer9   Úto_dictÚis_encoder_decoderÚbos_token_idÚdecoder_start_token_idr>   r6   r   r?   Ú	processorr   Ú_get_ngram_scoreÚ_get_ngram_score_cached)Úselfr3   r4   r5   r6   r7   s   &&&&&&r"   Ú__init__ÚWatermarkDetector.__init__{   s¢   € ô Ð-¬t×4Ò4Ø"5×"=Ñ"=Ó"?Ðð .:×-L×-LÐ-LˆL×%Ò%ÐR^×RuÑRuð 	Ôð  3Ð3DÕEˆÔØ&<Ô#Ü1ñ 
Ø#×.Ñ.ð
Ø7=ð
ØATñ
ˆŒô
 (1¸Õ'HÈ×I^ÑI^Ó'_ˆÖ$r%   c                ó:   <€ V ^8„  d   QhRS[ P                  RS[/# )r   ÚprefixÚtarget)ÚtorchÚ
LongTensorr;   )r    r!   s   "€r"   r#   r<   ’   s!   ø€ ÷ 'ñ '¡u×'7Ñ'7ð 'Áñ 'r%   c                ó@   € V P                   P                  V4      pW#9   # ©N)rF   Ú_get_greenlist_ids)rI   rM   rN   Úgreenlist_idss   &&& r"   rG   Ú"WatermarkDetector._get_ngram_score’   s   € ØŸ™×9Ñ9¸&ÓAˆØÑ&Ð&r%   c                ó4   <€ V ^8„  d   QhRS[ P                  /# )r   Ú	input_ids)rO   rP   )r    r!   s   "€r"   r#   r<   –   s   ø€ ÷ @ñ @±%×2BÑ2Bñ @r%   c           	     óþ  € VP                   w  r#\        V P                  P                  R 8H  4      pV P                  P                  ^,           V,
          p\
        P                  ! V4      P                  ^ 4      \
        P                  ! W5,
          ^,           4      P                  ^4      ,           pVRV3,          p\        P                  ! V4      p\        P                  ! V4      p	\        VP                   ^ ,          4       Fô  p
\        P                  ! Wz,          4      p/ pV F.  pV'       d   TMVRR pVR,          pV P                  Wï4      WÍ&   K0  	  V P                  '       d9   \        VP!                  4       4      WŠ&   \#        VP%                  4       4      Wš&   KŸ  \#        VP%                  4       4      WŠ&   \#        R \'        VP%                  4       VP%                  4       4       4       4      Wš&   Kö  	  W‰3# )ÚselfhashºNNNNc              3   ó6   "  € T F  w  rW,          x € K  	  R # 5irR   r&   )Ú.0ÚfreqÚoutcomes   &  r"   Ú	<genexpr>Ú=WatermarkDetector._score_ngrams_in_passage.<locals>.<genexpr>®   s   é € ð 9á)l™˜ð —N’NÛ)lùs   ‚éÿÿÿÿ)Úshaper;   rF   Úseeding_schemeÚcontext_widthrO   ÚarangeÚ	unsqueezer   ÚzerosÚrangeÚcollectionsÚCounterrH   r6   ÚlenÚkeysÚsumÚvaluesÚzip)rI   rW   Ú
batch_sizeÚ
seq_lengthrY   ÚnÚindicesÚngram_tensorsÚnum_tokens_scored_batchÚgreen_token_count_batchÚ	batch_idxÚfrequencies_tableÚngram_to_watermark_lookupÚngram_examplerM   rN   s   &&              r"   Ú_score_ngrams_in_passageÚ*WatermarkDetector._score_ngrams_in_passage–   s«  € Ø!*§¡Ñˆ
Ü�t—~‘~×4Ñ4¸
ÑBÓCˆØ�N‰N×(Ñ(¨1Õ,¨xÕ7ˆÜ—,’,˜q“/×+Ñ+¨AÓ.´·²¸j½nÈqÕ>PÓ1Q×1[Ñ1[Ð\]Ó1^Õ^ˆØ! ! W *Õ-ˆä"$§(¢(¨:Ó"6ÐÜ"$§(¢(¨:Ó"6ÐÜ˜}×2Ñ2°1Õ5Ö6ˆIÜ +× 3Ò 3°MÕ4LÓ MÐØ(*Ð%Û!2�ß*2™¸ÀcÀrÐ8J�Ø& rÕ*�Ø;?×;WÑ;WÐX^Ó;gÐ)Ó8ñ "3ð
 ×*×*Ð*ô 69Ð9J×9OÑ9OÓ9QÓ5RÐ'Ñ2Ü58Ð9R×9YÑ9YÓ9[Ó5\Ð'Ó2ä58Ð9J×9QÑ9QÓ9SÓ5TÐ'Ñ2Ü58ñ 9ä),Ð->×-EÑ-EÓ-GÐIb×IiÑIiÓIkÔ)ló9ó 6Ð'Ó2ñ 7ð& 'Ð?Ð?r%   c                óh   <€ V ^8„  d   QhRS[ P                  RS[ P                  RS[ P                  /# )r   Úgreen_token_countÚtotal_num_tokensÚreturnr   )r    r!   s   "€r"   r#   r<   ´   s4   ø€ ÷ ñ ±"·*±*ð ÑPR×PZÑPZð Ñ_a×_iÑ_iñ r%   c                ó    € V P                   pWV,          ,
          p\        P                  ! W#,          ^V,
          ,          4      pWE,          pV# )é   )r>   r   Úsqrt)rI   r~   r   Úexpected_countÚnumerÚdenomÚzs   &&&    r"   Ú_compute_z_scoreÚ"WatermarkDetector._compute_z_score´   sC   € Ø×-Ñ-ˆØ!Ð5EÕ$EÕEˆÜ—’Ð(Õ9¸QÀÕ=OÕPÓQˆØ�MˆØˆr%   c           
     ó   € W,
          V,          p^R^\         P                  ! V4      ^\         P                  ! RV^,          ,          \         P                  ,          4      ,
          ,          ,           ,          ,
          # )r‚   ç      à?éþÿÿÿ)r   ÚsignÚexpÚpi)rI   ÚxÚlocÚscaler‡   s   &&&& r"   Ú_compute_pvalÚWatermarkDetector._compute_pval»   sO   € Ø�W˜ÕˆØ�C˜1œrŸwšw q›z¨Q´·²¸¸QÀ½T½	ÄBÇEÁEÕ8IÓ1JÕ-JÕKÕKÕLÕMÐMr%   c          	      ój   <€ V ^8„  d   QhRS[ P                  RS[RS[RS[S[P                  ,          /# )r   rW   Úz_thresholdÚreturn_dictr€   )rO   rP   Úfloatr:   r   r   r   )r    r!   s   "€r"   r#   r<   ¿   sB   ø€ ÷ 1ñ 1á×#Ñ#ð1ñ ð1ñ ð	1ñ
 
!¡2§:¡:Õ	-ñ1r%   c           
     ó¸  € VR,          V P                   8X  d
   VR,          pVP                  R,          V P                  P                  ,
          ^8  d$   \	        RV P                  P                   R24      hV P                  V4      w  rEV P                  WT4      pWb8„  pV'       d3   V P                  V4      p^V,
          p	\        VVWT,          VVVV	R7      # V# )a  
        Args:
        input_ids (`torch.LongTensor`):
            The watermark generated text. It is advised to remove the prompt, which can affect the detection.
        z_threshold (`Dict`, *optional*, defaults to `3.0`):
            Changing this threshold will change the sensitivity of the detector. Higher z threshold gives less
            sensitivity and vice versa for lower z threshold.
        return_dict (`bool`,  *optional*, defaults to `False`):
            Whether to return `~generation.WatermarkDetectorOutput` or not. If not it will return boolean predictions,
ma
        Return:
            [`~generation.WatermarkDetectorOutput`] or `np.ndarray`: A [`~generation.WatermarkDetectorOutput`]
            if `return_dict=True` otherwise a `np.ndarray`.

zEMust have at least `1` token to score after the first min_prefix_len=z' tokens required by the seeding scheme.)r   r   r   r   r   r   r   )r   r   )rZ   :r‚   NNra   )	rD   rb   rF   rd   Ú
ValueErrorr{   rˆ   r“   r   )
rI   rW   r–   r—   r   r~   r   r   r   r   s
   &&&&      r"   Ú__call__ÚWatermarkDetector.__call__¿   sã   € ð. �T�?˜d×/Ñ/Ô/Ø! %Õ(ˆIà�?‰?˜2Õ §¡×!=Ñ!=Õ=ÀÔAÜð"Ø"&§.¡.×">Ñ">Ð!?Ð?fðhóð ð
 04×/LÑ/LÈYÓ/WÑ,ÐØ×'Ñ'Ð(9ÓMˆØÑ*ˆ
çØ×(Ñ(¨Ó1ˆGØ˜W�ˆJä*Ø"3Ø!2Ø0ÕDØØØ%Ø%ôð ð Ðr%   )rH   rD   r>   r6   rF   N)Fé€   )r   r‚   )g      @F)r'   r(   r)   r*   r+   rJ   rG   r{   rˆ   r“   r›   r-   r.   r/   s   @r"   r1   r1   G   sL   ø‡ € ñ1÷f`ò `÷.'ð '÷@ð @÷<ð ôN÷1÷ 1ð 1r%   r1   c                   óL   a a€ ] tR t^ót oRtRV3R lV 3R llltR tRtVtV ;t	# )ÚBayesianDetectorConfiga2  
This is the configuration class to store the configuration of a [`BayesianDetectorModel`]. It is used to
instantiate a Bayesian Detector model according to the specified arguments.

Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.

Args:
    watermarking_depth (`int`, *optional*):
        The number of tournament layers.
    base_rate (`float1`, *optional*, defaults to 0.5):
        Prior probability P(w) that a text is watermarked.
c                ó4   <€ V ^8„  d   QhRS[ R,          RS[/# )r   Úwatermarking_depthNÚ	base_rate)r;   r˜   )r    r!   s   "€r"   r#   Ú#BayesianDetectorConfig.__annotate__  s   ø€ ÷ #ñ #©3°­:ð #Éñ #r%   c                ó\   <€ Wn         W n        R V n        R V n        \        SV `  ! R/ VB  R # )Nr&   )r¡   r¢   Ú
model_namer5   ÚsuperrJ   )rI   r¡   r¢   ÚkwargsÚ	__class__s   &&&,€r"   rJ   ÚBayesianDetectorConfig.__init__  s-   ø€ Ø"4ÔØ"ŒàˆŒØ#'ˆÔ ä‰ÒÑ"˜6Ô"r%   c                ó   € Wn         W n        R # rR   )r¥   r5   )rI   r¥   r5   s   &&&r"   Úset_detector_informationÚ/BayesianDetectorConfig.set_detector_information  s   € Ø$ŒØ#6Ö r%   )r¢   r¥   r5   r¡   )Nr‹   )
r'   r(   r)   r*   r+   rJ   r«   r-   r.   Ú__classcell__©r¨   r!   s   @@r"   rŸ   rŸ   ó   s   ù‡ € ñ÷#õ #÷7ò 7r%   rŸ   c                   ó8   a € ] tR tRt o RtRtRtV 3R ltRtV t	R# )Ú$BayesianWatermarkDetectorModelOutputi  a@  
Base class for outputs of models predicting if the text is watermarked.

Args:
    loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
        Language modeling loss.
    posterior_probabilities (`torch.FloatTensor` of shape `(1,)`):
        Multiple choice classification loss.
Nc                óv   <€ V ^8„  d   Qh/ S[ P                  R,          ;R&   S[ P                  R,          ;R&   # )r   NÚlossÚposterior_probabilities)rO   ÚFloatTensor)r    r!   s   "€r"   r#   Ú1BayesianWatermarkDetectorModelOutput.__annotate__  s5   ø‡ ‚ ñ ×
Ñ
˜dÕ
"Ñ)ñ ñ #×.Ñ.°Õ5Ñ<ò r%   r&   )
r'   r(   r)   r*   r+   r²   r³   r,   r-   r.   r/   s   @r"   r°   r°     s   ø‡ € ñð &*€DØ8<Ð÷ ƒ r%   r°   c                   óf   a a€ ] tR tRt oRtV3R lV 3R lltV3R lR ltV3R lR ltR	tVt	V ;t
# )
Ú%BayesianDetectorWatermarkedLikelihoodi   zvWatermarked likelihood model for binary-valued g-values.

This takes in g-values and returns p(g_values|watermarked).
c                ó    <€ V ^8„  d   QhRS[ /# )r   r¡   )r;   )r    r!   s   "€r"   r#   Ú2BayesianDetectorWatermarkedLikelihood.__annotate__&  s   ø€ ÷ pñ p©3ñ pr%   c           	     óX  <€ \         SV `  4        Wn        \        P                  P                  RR\        P                  ! ^^V4      ,          ,           4      V n        \        P                  P                  R\        P                  ! ^^V P                  V4      ,          4      V n        R# )z!Initializes the model parameters.gü©ñÒMbP?Ng      À)	r¦   rJ   r¡   rO   r   Ú	ParameterÚrandnÚbetaÚdelta)rI   r¡   r¨   s   &&€r"   rJ   Ú.BayesianDetectorWatermarkedLikelihood.__init__&  ss   ø€ ä‰ÑÔØ"4ÔÜ—H‘H×&Ñ& t¨e´e·k²kÀ!ÀQÐHZÓ6[Õ.[Õ'[Ó\ˆŒ	Ü—X‘X×'Ñ'¨´·²¸A¸qÀ$×BYÑBYÐ[mÓ0nÕ(nÓoˆŽ
r%   c                óx   <€ V ^8„  d   QhRS[ P                  RS[S[ P                  S[ P                  3,          /# ©r   Úg_valuesr€   )rO   ÚTensorÚtuple)r    r!   s   "€r"   r#   r¹   -  s1   ø€ ÷ 7ñ 7©¯©ð 7¹%ÁÇÁÉeÏlÉlÐ@ZÕ:[ñ 7r%   c                ó®  € \         P                  ! \         P                  ! VRR7      V P                  RR7      p\         P                  ! VRR7      pV P
                  R,          VP                  V P
                  P                  4      R,          ,          P                  4       V P                  ,           p\         P                  ! V4      p^V,
          pWT3# )a  Computes the unique token probability distribution given g-values.

Args:
    g_values (`torch.Tensor` of shape `(batch_size, seq_len, watermarking_depth)`):
        PRF values.

Returns:
    p_one_unique_token and p_two_unique_tokens, both of shape
    [batch_size, seq_len, watermarking_depth]. p_one_unique_token[i,t,l]
    gives the probability of there being one unique token in a tournament
    match on layer l, on timestep t, for batch item i.
    p_one_unique_token[i,t,l] + p_two_unique_token[i,t,l] = 1.
©Údim)Úaxis)ÚdiagonalrŒ   ra   ).NrZ   ).N)rO   Úrepeat_interleaverf   r¡   Útrilr¾   ÚtypeÚdtypeÚsqueezer½   Úsigmoid)rI   rÂ   r�   ÚlogitsÚp_two_unique_tokensÚp_one_unique_tokens   &&    r"   Ú_compute_latentsÚ6BayesianDetectorWatermarkedLikelihood._compute_latents-  s¢   € ô& ×#Ò#¤E§O¢O°HÀ"Ô$EÀt×G^ÑG^ÐegÔhˆô �JŠJ�q 2Ô&ˆð —*‘*˜\Õ*¨Q¯V©V°D·J±J×4DÑ4DÓ-EÀiÕ-PÕP×YÑYÓ[Ð^b×^gÑ^gÕgˆä#Ÿmšm¨FÓ3ÐØÐ!4Õ4ÐØ!Ð6Ð6r%   c                óN   <€ V ^8„  d   QhRS[ P                  RS[ P                  /# rÁ   ©rO   rÃ   )r    r!   s   "€r"   r#   r¹   M  s'   ø€ ÷ Sñ S¡§¡ð S±·±ñ Sr%   c                ód   € V P                  V4      w  r#RVR,           V,          V,           ,          # )a  Computes the likelihoods P(g_values|watermarked).

Args:
    g_values (`torch.Tensor` of shape `(batch_size, seq_len, watermarking_depth)`):
        g-values (values 0 or 1)

Returns:
    p(g_values|watermarked) of shape [batch_size, seq_len, watermarking_depth].
r‹   )rÓ   )rI   rÂ   rÒ   rÑ   s   &&  r"   ÚforwardÚ-BayesianDetectorWatermarkedLikelihood.forwardM  s5   € ð 37×2GÑ2GÈÓ2QÑ/Ðð �x #•~Ð)<Õ<Ð?QÕQÕRÐRr%   )r½   r¾   r¡   )r'   r(   r)   r*   r+   rJ   rÓ   rØ   r-   r.   r­   r®   s   @@r"   r·   r·      s3   ù‡ € ñ÷
pó p÷7ð 7÷@S÷ Sð Sr%   r·   c                   óœ   a a€ ] tR tRt oRtRtV 3R lt]P                  ! 4       R 4       t	V3R lR lt
RV3R lR	 lltV3R
 ltRtVtV ;t# )ÚBayesianDetectorModeli^  a  
Bayesian classifier for watermark detection.

This detector uses Bayes' rule to compute a watermarking score, which is the sigmoid of the log of ratio of the
posterior probabilities P(watermarked|g_values) and P(unwatermarked|g_values). Please see the section on
BayesianScore in the paper for further details.
Paper URL: https://www.nature.com/articles/s41586-024-08025-4

Note that this detector only works with non-distortionary Tournament-based watermarking using the Bernoulli(0.5)
g-value distribution.

This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
etc.)

This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
and behavior.

Parameters:
    config ([`BayesianDetectorConfig`]): Model configuration class with all the parameters of the model.
        Initializing with a config file does not load the weights associated with the model, only the
        configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
Úmodelc                ó&  <€ \         SV `  V4       VP                  V n        VP                  V n        \	        V P                  R 7      V n        \        P                  P                  \        P                  ! V P                  .4      4      V n
        R# ))r¡   N)r¦   rJ   r¡   r¢   r·   Úlikelihood_model_watermarkedrO   r   r»   ÚtensorÚprior)rI   Úconfigr¨   s   &&€r"   rJ   ÚBayesianDetectorModel.__init__{  si   ø€ Ü‰Ñ˜Ô à"(×";Ñ";ˆÔØ×)Ñ)ˆŒÜ,QØ#×6Ñ6ô-
ˆÔ)ô —X‘X×'Ñ'¬¯ª°d·n±nÐ5EÓ(FÓGˆŽ
r%   c                ó�   € \        V\        P                  4      '       d&   \        P                  ! VP
                  RRR7       R# R# )zInitialize the weights.g        g{®Gáz”?)ÚmeanÚstdN)rA   r   r»   ÚinitÚnormal_Úweight)rI   Úmodules   &&r"   Ú_init_weightsÚ#BayesianDetectorModel._init_weights…  s.   € ô �fœbŸl™l×+Ò+Ü�LŠL˜Ÿ™¨S°d×;ñ ,r%   c          
      óˆ   <€ V ^8„  d   QhRS[ P                  RS[ P                  RS[ P                  RS[RS[ P                  /# )r   Úlikelihoods_watermarkedÚlikelihoods_unwatermarkedÚmaskrà   r€   )rO   rÃ   r˜   )r    r!   s   "€r"   r#   Ú"BayesianDetectorModel.__annotate__‹  sM   ø€ ÷ (1ñ (1á!&§¡ð(1ñ $)§<¡<ð(1ñ �l‰lð	(1ñ
 ð(1ñ 
�‰ñ(1r%   c           	     ó2  € \         P                  ! VRR7      p\         P                  ! VRRR7      p\         P                  ! \         P                  ! VR\	        R4      R7      4      p\         P                  ! \         P                  ! VR\	        R4      R7      4      pWV,
          p\         P
                  ! RWs,          4      p\         P                  ! V4      \         P                  ! ^V,
          4      ,
          p	W˜,           p
\         P                  ! V
4      # )	aÏ  
Compute posterior P(w|g) given likelihoods, mask and prior.

Args:
    likelihoods_watermarked (`torch.Tensor` of shape `(batch, length, depth)`):
        Likelihoods P(g_values|watermarked) of g-values under watermarked model.
    likelihoods_unwatermarked (`torch.Tensor` of shape `(batch, length, depth)`):
        Likelihoods P(g_values|unwatermarked) of g-values under unwatermarked model.
    mask (`torch.Tensor` of shape `(batch, length)`):
        A binary array indicating which g-values should be used. g-values with mask value 0 are discarded.
    prior (`float`):
        the prior probability P(w) that the text is watermarked.

Returns:
    Posterior probability P(watermarked|g_values), shape [batch].
rÆ   çñhãˆµøä>)ÚminÚmaxg ÂëþKH´9Úinfzi...->ira   çwJëÿï?)rO   rf   ÚclampÚlogr˜   ÚeinsumrÏ   )rI   rí   rî   rï   rà   Úlog_likelihoods_watermarkedÚlog_likelihoods_unwatermarkedÚlog_oddsÚrelative_surprisal_likelihoodÚrelative_surprisal_priorÚrelative_surprisals   &&&&&      r"   Ú_compute_posteriorÚ(BayesianDetectorModel._compute_posterior‹  sÍ   € ô. �Š˜t¨Ô,ˆÜ—’˜E t°Ô:ˆÜ&+§i¢i´·²Ð<SÐY^ÔdiÐjoÓdpÔ0qÓ&rÐ#Ü(-¯	ª	´%·+²+Ð>WÐ]bÔhmÐnsÓhtÔ2uÓ(vÐ%Ø.ÕNˆô ).¯ª°YÀÅÓ(PÐ%ô $)§9¢9¨UÓ#3´e·i²iÀÀEÅ	Ó6JÕ#JÐ ð 6ÕUÐô �}Š}Ð/Ó0Ð0r%   c                ó|   <€ V ^8„  d   QhRS[ P                  RS[ P                  RS[ P                  R,          RS[/# )r   rÂ   rï   ÚlabelsNr€   )rO   rÃ   r°   )r    r!   s   "€r"   r#   rð   µ  sJ   ø€ ÷ )\ñ )\á—,‘,ð)\ñ �l‰lð)\ñ —‘˜tÕ#ð	)\ñ 
.ñ)\r%   c                ó¶  € V P                  V4      pR\        P                  ! V4      ,          pV P                  VVVV P                  R7      pRp	Vej   \        4       p
\        P                  ! V P                   P                  ^,          4      pW´,          pV
! \        P                  ! VRR4      V4      V,           p	V'       g   V	f   V3# W‰3# \        W˜R7      # )aœ  
Computes the watermarked posterior P(watermarked|g_values).

Args:
    g_values (`torch.Tensor` of shape `(batch_size, seq_len, watermarking_depth, ...)`):
        g-values (with values 0 or 1)
    mask:
        A binary array shape [batch_size, seq_len] indicating which g-values should be used. g-values with mask
        value 0 are discarded.

Returns:
    p(watermarked | g_values), of shape [batch_size].
r‹   )rí   rî   rï   rà   Nrò   )r²   r³   rö   )
rÞ   rO   Ú	ones_liker   rà   r	   rm   r¾   r÷   r°   )rI   rÂ   rï   r  Úloss_batch_weightr—   rí   rî   Úoutr²   Úloss_fctÚloss_unwweightÚloss_weights   &&&&&&       r"   rØ   ÚBayesianDetectorModel.forwardµ  sÉ   € ð, #'×"CÑ"CÀHÓ"MÐØ$'¬%¯/ª/¸(Ó*CÕ$CÐ!Ø×%Ñ%Ø$;Ø&?ØØ—*‘*ð	 &ó 
ˆð ˆØÒÜ“yˆHÜ"ŸYšY t×'HÑ'H×'NÑ'NÐPQÕ'QÓRˆNØ(Õ<ˆKÙœEŸKšK¨¨T°8Ó<¸fÓEÈÕSˆDçØ!š\�C�6Ð:°¨{Ð:ä3¸Ô[Ð[r%   c                ó&   <€ V ^8„  d   Qh/ S[ ;R&   # )r   rá   )rŸ   )r    r!   s   "€r"   r#   rð   ^  s   ø‡ ‚ ñ4 #Ñ"ò5 r%   )r¢   rÞ   rà   r¡   )Nr‚   F)r'   r(   r)   r*   r+   Úbase_model_prefixrJ   rO   Úno_gradrê   r   rØ   r,   r-   r.   r­   r®   s   @@r"   rÛ   rÛ   ^  sQ   ù‡ € ñð4  ÐõHð ‡]‚]ƒ_ñ<ó ð<÷
(1ð (1÷T)\ò )\÷o … r%   rÛ   c                   óH   a € ] tR tRt o RtV 3R lR ltV 3R lR ltRtV tR# )	ÚSynthIDTextWatermarkDetectoriá  aE  
SynthID text watermark detector class.

This class has to be initialized with the trained bayesian detector module check script
in examples/synthid_text/detector_training.py for example in training/saving/loading this
detector module. The folder also showcases example use case of this detector.

Parameters:
    detector_module ([`BayesianDetectorModel`]):
        Bayesian detector module object initialized with parameters.
        Check https://github.com/huggingface/transformers-research-projects/tree/main/synthid_text for usage.
    logits_processor (`SynthIDTextWatermarkLogitsProcessor`):
        The logits processor used for watermarking.
    tokenizer (`Any`):
        The tokenizer used for the model.

Examples:
```python
>>> from transformers import (
...     AutoTokenizer, BayesianDetectorModel, SynthIDTextWatermarkLogitsProcessor, SynthIDTextWatermarkDetector
... )

>>> # Load the detector. See https://github.com/huggingface/transformers-research-projects/tree/main/synthid_text for training a detector.
>>> detector_model = BayesianDetectorModel.from_pretrained("joaogante/dummy_synthid_detector")
>>> logits_processor = SynthIDTextWatermarkLogitsProcessor(
...     **detector_model.config.watermarking_config, device="cpu"
... )
>>> tokenizer = AutoTokenizer.from_pretrained(detector_model.config.model_name)
>>> detector = SynthIDTextWatermarkDetector(detector_model, logits_processor, tokenizer)

>>> # Test whether a certain string is watermarked
>>> test_input = tokenizer(["This is a test input"], return_tensors="pt")
>>> is_watermarked = detector(test_input.input_ids)
```
c                ó,   <€ V ^8„  d   QhRS[ RS[RS[/# )r   Údetector_moduleÚlogits_processorÚ	tokenizer)rÛ   r   r   )r    r!   s   "€r"   r#   Ú)SynthIDTextWatermarkDetector.__annotate__  s)   ø€ ÷ #ñ #á.ð#ñ >ð#ñ ñ	#r%   c                ó*   € Wn         W n        W0n        R # rR   ©r  r  r  )rI   r  r  r  s   &&&&r"   rJ   Ú%SynthIDTextWatermarkDetector.__init__  s   € ð  /ÔØ 0ÔØ"Žr%   c                ó4   <€ V ^8„  d   QhRS[ P                  /# )r   Útokenized_outputsrÖ   )r    r!   s   "€r"   r#   r    s   ø€ ÷ =ñ =©%¯,©,ñ =r%   c                óR  € V P                   P                  VV P                  P                  R 7      RV P                   P                  ^,
          R13,          pV P                   P                  VR7      pW2,          pV P                   P                  VR7      pV P                  WT4      # ))rW   Úeos_token_idrZ   N)rW   )r  Úcompute_eos_token_maskr  r  Ú	ngram_lenÚcompute_context_repetition_maskÚcompute_g_valuesr  )rI   r  Úeos_token_maskÚcontext_repetition_maskÚcombined_maskrÂ   s   &&    r"   r›   Ú%SynthIDTextWatermarkDetector.__call__  s°   € ð ×.Ñ.×EÑEØ'ØŸ™×4Ñ4ð Fó 
ð ˆT×"Ñ"×,Ñ,¨qÕ0Ñ2Ð
2õ4ˆð #'×"7Ñ"7×"WÑ"WØ'ð #Xó #
Ðð
 0Õ@ˆà×(Ñ(×9Ñ9Ø'ð :ó 
ˆð ×#Ñ# HÓ<Ð<r%   r  N)	r'   r(   r)   r*   r+   rJ   r›   r-   r.   r/   s   @r"   r  r  á  s   ø‡ € ñ"÷H#ð #÷=ö =r%   r  )(ri   Údataclassesr   Ú	functoolsr   Útypingr   r   r   Únumpyr   rO   r   Útorch.nnr	   Ú r
   ræ   Úconfiguration_utilsr   Úmodeling_utilsr   Úutilsr   r   Úlogits_processr   r   r   Ú
get_loggerr'   Úloggerr   r1   rŸ   r°   ÚModuler·   rÛ   r  r&   r%   r"   Ú<module>r2     sÈ   ðó Ý !Ý ß ,Ñ ,ã Û Ý Ý å %Ý 2Ý ,ß (ß Y÷ Ý7à	×	Ò	˜HÓ	%€ð ÷)ð )ó ð)÷@iñ iôX7Ð-ô 7ð: ô=¨;ó =ó ð=ô;S¨B¯I©Iô ;Sô|@\˜Oô @\÷FC=ó C=r%   