
    Nj!              	       h   d dl Z d dlmZ d dlZd dlmZ d dlmZ d dlmZ d dl	m
Z
 d dlmZ d dlmZ d d	lmZ  e j"                  e      Zeej(                  ej(                  ej(                  gej(                  f   Zdd
edej(                  dedej(                  fdZ G d dej0                        Zy)    N)partial)Callable)nn)Self)LUTConditioner)StreamingTransformer)SimpleMLPAdaLN)FlowLMConfigv_tx_0	num_stepsreturnc                     |}t        |      D ][  }||z  }|dz   |z  } | |t        j                  |dddf         z  |t        j                  |dddf         z  |      }|||z  z  }] |S )at  Rebuilds the data sample from starting point x_0.

    Lagrangian Self Distillation (https://arxiv.org/pdf/2505.18825)

    Args:
        v_t: Function taking t and x_t as input and returning the flow.
        x_0: Starting point from the known distribution.
        num_steps: Number of steps to take.

    Returns:
        x_1_hat: (B, D) Reconstructed data sample.
       .N)rangetorch	ones_like)r   r   r   currentistflow_dirs           j/Users/ahmed/devFolder/Ultron/claude-voice/.venv/lib/python3.12/site-packages/pocket_tts/models/flow_lm.py
lsd_decoder      s     G9	MUiC!G--q5??3sBQBw<3P/PRY
 	8i''  N    c                       e Zd ZdZ	 	 	 	 	 	 ddedededededed	ed
e	f fdZ
edefd       Zdej                  dej                  dededededz  dedeej                  ej                  f   fdZdej                  dedej                  fdZdej                  dej                  dededededz  dedeej                  ej                  f   fdZededed
e	defd       Z xZS )FlowLMModela  Transformer-based flow language model on multiple streams of latents.

    Args:
        conditioner (LUTConditioner): Text conditioner for processing text inputs.
        flow: Flow module that defines the flow loss and sampling strategy.
        flow_net: Trainable function (cond, t, x_t) -> u_t.
        dim (int): Dimension of the transformer encoder.
        norm (str): Normalization method.
        attribute_dropouts (dict): Attribute dropout probabilities.
        ldim (int): Latent dimension.
        stats_ema_decay (float): Decay for the EMA of the latent statistics.
        **kwargs: Additional parameters for the transformer encoder.
    Nconditionerflow_nettransformerdimldimstats_ema_decaytext_padding_weightinsert_bos_before_voicec
                    t         
|           || _        || _        || _        || _        || _        || _        || _        | j                  dt        j                  ||             | j                  dt        j                  ||             t        j                  j                  t        j                  ||            | _        |	| _        | j"                  rFt        j                  j                  t        j                  dd| j
                  f|            | _        t        j&                  | j                  |d|      | _        || _        t        j,                  |d      | _        t        j&                  |d|      | _        y )	Nemb_std)dtypeemb_meanr   F)biasr(   gh㈵>)eps)super__init__r   r"   r#   r!   r$   r(   r   register_bufferr   oneszerosr   	Parameterrandnbos_embr%   bos_before_voiceLinearinput_linearr    	LayerNormout_normout_eos)selfr   r   r    r!   r"   r#   r$   r(   r%   	__class__s             r   r-   zFlowLMModel.__init__:   s#    	&	.#6 
 Y

4u(EFZT)GHxx))%++d%*HI'>$''$)HH$6$6u{{Aq$((CS[`7a$bD!IIdii5N&Sd3yyau5r   r   c                 \    t        | j                               j                  j                  S )N)next
parametersdevicetype)r:   s    r   r?   zFlowLMModel.device\   s     DOO%&--222r   sequencetext_embeddingsmodel_statelsd_decode_stepstempnoise_clampeos_thresholdc                    t        j                  t        j                  |      | j                  |      }| j	                  |      }| j                  ||||      }	|	j                  t         j                        }	|dkD  sJ |	dddf   }	| j                  |	      |kD  }
|	j                  dd | j                  fz   }|dz  }t        j                  ||	j                  |	j                        }|-t         j                  j                  j!                  |d|       n/t         j                  j                  j#                  |d|| |	       t%        | j&                  |	      }t)        |||      |
fS )
a  Apply language model on sequence and conditions.
        Given a tensor of sequence of shape [B, S, ldim], returns the loss in training mode
        or the reconstructed latent in generation mode.

        Args:
            sequence (torch.Tensor): Latents to model.
            text_embeddings (torch.Tensor): Pre-computed conditioning
                tensor.
            lsd_decode_steps (int): Number of steps to decode when generating audio.
                If zero, the model computes the loss.
        Returns:
            (output, eos_output, metrics). If `lsd_decode_steps` is zero, `output` is the loss tensor of shape [B, S],
            otherwise it is the reconstructed latent.
        )rC   r   Ng      ?)r(   r?   g        )meanstd)rJ   rK   ab)r   whereisnanr3   r6   backbonetofloat32r9   shaper"   emptyr(   r?   r   initnormal_trunc_normal_r   r   r   )r:   rA   rB   rC   rD   rE   rF   rG   input_transformer_outr9   noise_shaperK   noiseconditioned_flows                  r   forwardzFlowLMModel.forward`   s?   2 ;;u{{84dllHM""8,--Wb-c),,U]];!###)!R%0,,/-?%++CR0DII<?CiK/D/D_McMcdHHMM!!%cs!;HHMM''CS[LT_'`"4==/B*E3CDgMMr   c                     t        j                  ||gd      }| j                  ||      }| j                  r| j                  |      }|d d |j                  d    d f   }|S )Nr   )r!   )r   catr    r8   rS   )r:   rX   rB   rA   rC   rY   s         r   rP   zFlowLMModel.backbone   sd     OV4!<**6;?=="mmO<O)!hnnQ.?-?-A*ABr   c           	      $     | |||||||      }|S )a  Sample next latent from the model given a sequence and a set of conditions.
        Args:
            sequence (torch.Tensor): Current sequence of shape [B, K, S]
                with K corresponding to the number of codebooks and S the number of sequence steps.
                S = 1 in streaming mode, except for the first step that contains a bigger prompt.
            text_embeddings (torch.Tensor): Condition tensor.
            n_steps (int): Number of flow steps to decode when generating audio.
        Returns:
            next_latent (torch.Tensor), is_eos (torch.Tensor): Next latent tensor of shape [B, 1, ldim]
                and is_eos tensor of shape [B, 1] with 1 on EOS positions.
        )rA   rB   rD   rE   rF   rG   rC    )	r:   rA   rB   rC   rD   rE   rF   rG   results	            r   _sample_next_latentzFlowLMModel._sample_next_latent   s*    * +-#'#
 r   config
latent_dimc                    |j                   j                  }t        j                  |||      }t	        |j
                  j                  t        |j
                  j                        |j
                  j                  |      }t        j                  |j                         } | |||||t        t        |j                        |      S )N)n_binstokenizer_pathr!   
output_dim)r   r    r!   r   r"   r(   r%   )r    d_modelr	   from_pydantic_configr   lookup_tablerg   strrh   r!   r   getattrr   r(   )clsrd   re   r%   rj   flow_mlpr   r    s           r   rk   z FlowLMModel.from_pydantic_config   s     $$,,!66vz7S$&&--v22AAB##''	
 +??@R@RS##%.$;
 	
r   )   @   g+?g      ?NF)__name__
__module____qualname____doc__r   r	   r   intfloatboolr-   propertyrm   r?   r   Tensordicttupler]   rP   rc   classmethodr
   r   rk   __classcell__)r;   s   @r   r   r   +   s   & !&%((- 6# 6 ! 6 *	 6
  6  6  6 # 6 "& 6D 3 3 3+N,,+N +N 	+N
 +N +N T\+N +N 
u||U\\)	*+NZ',||LP	$,,  	
   T\  
u||U\\)	*B 
!
/2
MQ
	
 
r   r   )r   )logging	functoolsr   r   beartype.typingr   r   typing_extensionsr   pocket_tts.conditioners.textr   #pocket_tts.modules.mimi_transformerr   pocket_tts.modules.mlpr	   pocket_tts.utils.configr
   	getLoggerrs   loggerr{   FlowNet2rw   r   Moduler   ra   r   r   <module>r      s       $  " 7 D 1 0			8	$U\\5<<>LMH 5<< C  0m
")) m
r   