File size: 16,814 Bytes
e70ad00
d72b2c3
 
 
 
 
e70ad00
d72b2c3
 
 
 
 
54adc39
d912185
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54adc39
 
d912185
 
 
d72b2c3
e366cd5
d72b2c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0ce150
d72b2c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e366cd5
 
 
 
 
d72b2c3
 
 
 
 
 
 
 
531e776
54adc39
d72b2c3
 
0a8807e
d72b2c3
 
 
 
 
 
 
 
a0ce150
 
 
 
 
 
 
 
 
 
 
 
 
 
d72b2c3
a0ce150
 
 
 
 
d72b2c3
 
e70ad00
d72b2c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0ce150
 
 
 
d72b2c3
 
 
 
 
 
 
 
 
 
 
 
 
3eec6d2
e366cd5
 
731cb10
a0ce150
731cb10
a0ce150
 
3eec6d2
54adc39
731cb10
 
 
d72b2c3
 
a0ce150
 
 
d72b2c3
e83a997
d72b2c3
a0ce150
 
 
d72b2c3
 
 
 
e366cd5
d72b2c3
 
e366cd5
 
a0ce150
 
d9889a1
a0ce150
d72b2c3
 
8639464
a0ce150
 
e366cd5
a0ce150
 
 
 
 
e366cd5
 
d72b2c3
 
 
 
8639464
d72b2c3
 
 
d9889a1
d72b2c3
d9889a1
 
d72b2c3
 
0a8807e
d72b2c3
0a8807e
27d24be
 
d9889a1
 
e366cd5
d72b2c3
d9889a1
a0ce150
 
 
 
 
 
d9889a1
a0ce150
 
 
 
 
 
 
731cb10
 
 
e366cd5
a0ce150
 
 
731cb10
 
 
a0ce150
731cb10
d912185
731cb10
a0ce150
 
731cb10
a0ce150
 
e366cd5
d9889a1
a0ce150
 
 
d9889a1
 
 
27d24be
d9889a1
 
 
 
 
 
27d24be
 
d9889a1
 
 
27d24be
 
 
 
 
 
 
 
 
 
 
 
 
d9889a1
27d24be
 
 
 
 
e366cd5
731cb10
 
 
 
e366cd5
a0ce150
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
from dataclasses import dataclass
import logging
import math
import typing as tp
import torch
import torch.nn.functional as F
from audiocraft.transformer import StreamingTransformer
from dataclasses import dataclass
from functools import partial
from torch import nn
from audiocraft.activations import get_activation_fn

def sample_top_k(p, k=1, n_draw=None):
    """
        p probabs 2048 ?
        num_draw : how many tokens to sample (for duplicate elongation)
    """

    p = torch.softmax(p, dim=-1)  # p/temp
         

    
    top_k_value, i250 = torch.topk(p, k, dim=-1)   # probs: [1, 4, 2048]
    # print('\n_____TOPK________\n', top_k_value.shape, top_k_value[0, 0, :10], '\n___________END_TOPK____________\n')
    min_value_top_k = top_k_value[..., [-1]]  # 
    p *= (p >= min_value_top_k).float()
    p.div_(p.sum(dim=-1, keepdim=True))
    # -- next_token = multinomial(probs, num_samples=num_draw)
    
    # RESHAPED into bs, 4, 250
    p_ = p.reshape(-1, p.shape[-1])
    
    
    out = torch.multinomial(p_,
                            num_samples=n_draw, 
                            replacement=False)  # [4, num_draw]
    return out.transpose(0, 1)[:, :, None]       # [num_draw, 4, 1]



# ============================================== From LM.py


logger = logging.getLogger(__name__)
TextCondition = tp.Optional[str]  # a text condition can be a string or None (if doesn't exist)
ConditionType = tp.Tuple[torch.Tensor, torch.Tensor]  # condition, mask

ConditionTensors = tp.Dict[str, ConditionType]
CFGConditions = tp.Union[ConditionTensors, tp.Tuple[ConditionTensors, ConditionTensors]]


def get_init_fn(method: str, input_dim: int, init_depth: tp.Optional[int] = None):
    """LM layer initialization.
    Inspired from xlformers: https://github.com/fairinternal/xlformers

    Args:
        method (str): Method name for init function. Valid options are:
            'gaussian', 'uniform'.
        input_dim (int): Input dimension of the initialized module.
        init_depth (int, optional): Optional init depth value used to rescale
            the standard deviation if defined.
    """
    # Compute std
    std = 1 / math.sqrt(input_dim)
    # Rescale with depth
    if init_depth is not None:
        std = std / math.sqrt(2 * init_depth)

    if method == 'gaussian':
        return partial(
            torch.nn.init.trunc_normal_, mean=0.0, std=std, a=-3 * std, b=3 * std
        )
    elif method == 'uniform':
        bound = math.sqrt(3) * std  # ensure the standard deviation is `std`
        return partial(torch.nn.init.uniform_, a=-bound, b=bound)
    else:
        raise ValueError("Unsupported layer initialization method")


def init_layer(m: nn.Module,
               method: str,
               init_depth: tp.Optional[int] = None,
               zero_bias_init: bool = False):
    """Wrapper around ``get_init_fn`` for proper initialization of LM modules.

    Args:
        m (nn.Module): Module to initialize.
        method (str): Method name for the init function.
        init_depth (int, optional): Optional init depth value used to rescale
            the standard deviation if defined.
        zero_bias_init (bool): Whether to initialize the bias to 0 or not.
    """
    if isinstance(m, nn.Linear):
        init_fn = get_init_fn(method, m.in_features, init_depth=init_depth)
        if m.weight.device.type == 'cpu' and m.weight.dtype == torch.float16:
            weight = m.weight.float()
            init_fn(weight)
            m.weight.data[:] = weight.half()
        else:
            init_fn(m.weight)
        if zero_bias_init and m.bias is not None:
            nn.init.constant_(m.bias, 0)
    elif isinstance(m, nn.Embedding):
        init_fn = get_init_fn(method, m.embedding_dim, init_depth=None)
        if m.weight.device.type == 'cpu' and m.weight.dtype == torch.float16:
            weight = m.weight.float()
            init_fn(weight)
            m.weight.data[:] = weight.half()
        else:
            init_fn(m.weight)


class ScaledEmbedding(nn.Embedding):
    """Boost learning rate for embeddings (with `scale`).
    """
    def __init__(self, *args, lr=None, **kwargs):
        super().__init__(*args, **kwargs)
        self.lr = lr

    def make_optim_group(self):
        group = {"params": list(self.parameters())}
        if self.lr is not None:
            group["lr"] = self.lr
        return group


@dataclass
class LMOutput:
    # The logits are already re-aligned with the input codes
    # hence no extra shift is required, e.g. when computing CE
    logits: torch.Tensor  # [B, K, T, card]
    mask: torch.Tensor  # [B, K, T]


class LMModel(nn.Module):
    """Transformer-based language model on multiple streams of codes.

    Args:
        pattern_provider (CodebooksPatternProvider): Pattern provider for codebook interleaving.
        condition_provider (MusicConditioningProvider): Conditioning provider from metadata.
        fuser (ConditionFuser): Fuser handling the fusing of conditions with language model input.
        n_q (int): Number of parallel streams to model.
        card (int): Cardinality, vocabulary size.
        dim (int): Dimension of the transformer encoder.
        num_heads (int): Number of heads for the transformer encoder.
        hidden_scale (int): Scale for hidden feed forward dimension of the transformer encoder.
        norm (str): Normalization method.
        norm_first (bool): Use pre-norm instead of post-norm.
        emb_lr (float, optional): Embedding-specific learning rate.
        bias_proj (bool): Use bias for output projections.
        weight_init (str, optional): Method for weight initialization.
        depthwise_init (str, optional): Method for depthwise weight initialization.
        zero_bias_init (bool): If true and bias in Linears, initialize bias to zeros.
        cfg_dropout (float): Classifier-free guidance dropout.
        cfg_coef (float): Classifier-free guidance coefficient.
        attribute_dropout (dict): Attribute dropout probabilities.
        two_step_cfg (bool): Whether to run classifier free-guidance with 2 distinct steps.
        **kwargs: Additional parameters for the transformer encoder.
    """
    def __init__(self,
                 pattern_provider, 
                 condition_provider,
                 fuser,
                 n_q: int = 8, card: int = 1024, dim: int = 128, num_heads: int = 8,
                 hidden_scale: int = 4, norm: str = 'layer_norm', norm_first: bool = False,
                 emb_lr: tp.Optional[float] = None, bias_proj: bool = True,
                 weight_init: tp.Optional[str] = None, depthwise_init: tp.Optional[str] = None,
                 zero_bias_init: bool = False, cfg_dropout: float = 0, cfg_coef: float = 1.0,
                 attribute_dropout: tp.Dict[str, tp.Dict[str, float]] = {}, two_step_cfg: bool = False,
                 **kwargs):
        super().__init__()
        self.cfg_coef = cfg_coef
        
        self.n_draw = 1
        self.condition_provider = condition_provider
        self.fuser = fuser
        self.card = card  # 2048 ?
        embed_dim = self.card + 1
        self.n_q = n_q
        self.dim = dim
        self.pattern_provider = pattern_provider
        self.two_step_cfg = two_step_cfg
        self.emb = nn.ModuleList([ScaledEmbedding(embed_dim, dim, lr=emb_lr) for _ in range(n_q)])
        if 'activation' in kwargs:
            kwargs['activation'] = get_activation_fn(kwargs['activation'])
        # ========================================================================
        #  {
        #   'dtype': torch.float16, 'device': 'cuda',
        #   'num_layers': 48, 'dropout': 0.0, 'activation': 'gelu', 
        #   'bias_ff': False, 'bias_attn': False,
        #   'past_context': None, 'causal': True, 
        #   'custom': False, 'memory_efficient': True,
        #   'attention_as_float32': False, 'positional_embedding': 'sin', 'xpos': False, 
        #   'checkpointing': 'none', 'cross_attention': True, 'qk_layer_norm': False,
        #   'qk_layer_norm_cross': False, 'attention_dropout': None, 'kv_repeat': 1
        #   }
        # ==========================================================================
        kwargs.pop('layer_scale')  # nn.Indentity()
        
        self.transformer = StreamingTransformer(
            d_model=dim, 
            num_heads=num_heads, 
            dim_feedforward=int(hidden_scale * dim),
            norm=norm, 
            norm_first=norm_first, **kwargs)
        self.out_norm: tp.Optional[nn.Module] = None
        if norm_first:
            self.out_norm = nn.LayerNorm(dim, eps=1e-5)
        self.linears = nn.ModuleList([nn.Linear(dim, self.card, bias=bias_proj) for _ in range(n_q)])
        self._init_weights(weight_init, depthwise_init, zero_bias_init)
        self._fsdp: tp.Optional[nn.Module]
        self.__dict__['_fsdp'] = None

    def _init_weights(self, weight_init: tp.Optional[str], depthwise_init: tp.Optional[str], zero_bias_init: bool):
        """Initialization of the transformer module weights.

        Args:
            weight_init (str, optional): Weight initialization strategy. See ``get_init_fn`` for valid options.
            depthwise_init (str, optional): Depthwise initialization strategy. The following options are valid:
                'current' where the depth corresponds to the current layer index or 'global' where the total number
                of layer is used as depth. If not set, no depthwise initialization strategy is used.
            zero_bias_init (bool): Whether to initialize bias to zero or not.
        """
        assert depthwise_init is None or depthwise_init in ['current', 'global']
        assert depthwise_init is None or weight_init is not None, \
            "If 'depthwise_init' is defined, a 'weight_init' method should be provided."
        assert not zero_bias_init or weight_init is not None, \
            "If 'zero_bias_init', a 'weight_init' method should be provided"

        if weight_init is None:
            return

        for emb_layer in self.emb:
            init_layer(emb_layer, method=weight_init, init_depth=None, zero_bias_init=zero_bias_init)

        for layer_idx, tr_layer in enumerate(self.transformer.layers):
            depth = None
            if depthwise_init == 'current':
                depth = layer_idx + 1
            elif depthwise_init == 'global':
                depth = len(self.transformer.layers)
            init_fn = partial(init_layer,
                              method=weight_init,
                              init_depth=depth, 
                              zero_bias_init=zero_bias_init)
            tr_layer.apply(init_fn)

        for linear in self.linears:
            init_layer(linear, method=weight_init, init_depth=None, zero_bias_init=zero_bias_init)

    @property
    def special_token_id(self) -> int:
        return self.card

    @property
    def num_codebooks(self) -> int:
        return self.n_q

    def forward(self,
                sequence,
                condition_tensors=None,
                token_count=None):
        B, K, S = sequence.shape    # linears are n_q
        input_ = sum([self.emb[k](sequence[:, k]) for k in range(K)])    
        # input_, cross_attention_input = self.fuser(input_, condition_tensors)
        cross_attention_input = condition_tensors['description'][0]
        
        # print(f'{input_.shape=}')
        out = self.transformer(input_,
                               cross_attention_src=cross_attention_input,
                               token_count=token_count)
        if self.out_norm:
            out = self.out_norm(out)
        # K = 2 because of llm producing 2 tokens?
        # so only 2 x sel.flinear() of 4 are used ?
        # WHy torch.stack is in dim=1    
        logits = torch.stack([self.linears[k](out) for k in range(K)], dim=1)  # [B, K, S, card]
        # print(f'{input_.shape=}  {out.shape=}  {cross_attention_input.shape=}  {logits.shape=} FUSER LLM')
        # remove the prefix from the model outputs
        # if len(self.fuser.fuse2cond['prepend']) > 0:
        #     logits = logits[:, :, -S:]
        #     print('==========================================PRESFIX')

        return logits  # [B, K, S, card]


    # GENERATE class revert_codebook_patterns()
    @torch.no_grad()
    def generate(self,
                 prompt = None,
                 conditions = [],
                 num_samples = 1,  # N next token
                 max_gen_len=256):
        
        print(f'{prompt=} {conditions=}')
        first_param = next(iter(self.parameters()))
        device = first_param.device
        
        
        
        tokenized = self.condition_provider.tokenize(conditions)
        # print('TOKENIZ', tokenized)  # 'description'
        # TOKENIZ {'description': {'input_ids': tensor([[3887,   16, 2815,    1],
        # [3887,   16, 2815,    1]], device='cuda:0'), 'attention_mask': tensor([[1, 1, 1, 1],
        # [1, 1, 1, 1]], device='cuda:0')}}

        cfg_conditions = self.condition_provider(tokenized)
        

        if prompt is None:
            assert num_samples > 0
            prompt = torch.zeros((num_samples, self.num_codebooks, 0), dtype=torch.long, device=device)
            print('\n\n\n\n DEFAULT PROMPT ZERO \n\n-')

        B, K, T = prompt.shape
        start_offset = T
        

        pattern = self.pattern_provider.get_pattern(max_gen_len)  # duplicate sequence
        # this token is used as default value for codes that are not generated yet ?
        unknown_token = -1

        
        gen_codes = torch.full((B, K, max_gen_len), unknown_token, dtype=torch.long, device=device)
        
        gen_codes[..., :start_offset] = prompt  # place 0
        
        _gen_sequence, _, mask = pattern.build_pattern_sequence(gen_codes, self.special_token_id)
        
        

        

        
        # --
        # print(mask.shape, mask.sum(), 'MSK LM')
        # torch.Size([4, 39]) tensor(140, device='cuda:0') MSK LM ? Fully 1 normal no special token
        # --\
            
        # list - Elongation for take-5 next tokens - n_draw 5 tokens at each time-step
        # append them at end of sequence
        duplicate_draw = [
            _gen_sequence[:, :, 0:1].repeat(self.n_draw, 1, 1)
                            ]
        
        
        for offset in range(1, _gen_sequence.shape[2]):
            
            
            
            
            
            
            logits = self.forward(_gen_sequence[:, :, offset-1:offset],  # bs/n_draw, 4, 1
                                  condition_tensors=cfg_conditions,
                                  token_count=offset)
            
            # print(f'BEF {logits.shape=} BEF utils.SampleTop5')  # AGREES 4 BEF logits.shape=torch.Size([1, 4, 1, 2048]) BEF utils.SampleTop5
            next_token = sample_top_k(logits, n_draw=self.n_draw)  # [1,4,2048] logits
            


            _gen_sequence[:, :, offset] = next_token[0, :, 0]  #  next_token=[1,4,6] gen_seq=[1, 4, 39]
            
            duplicate_draw.append(next_token)
            
    
            

        gen_sequence = torch.cat(duplicate_draw, 2)  # RESHAPE -> N_DRAW -> TIME
        
        # revert codes as "batch"
        
        
        # In decoder - flatten
        
        # _, tokd, len_seq = gen_sequence.shape 
        # gen_sequence = gen_sequence.transpose(0, 1).reshape(tokd, self.n_draw * len_seq)[None, :, :]
        
        print(f' <=> BEFORE CODES {gen_sequence.shape=} {_gen_sequence.shape=}\n')   # ARRIVES here also if special
        
        # revert_pattern_logits ~ NOT CALLED EXPLICIT
        out_codes, _, _ = pattern.revert_pattern_sequence(gen_sequence, 
                                                          special_token=unknown_token)
        
        
        # set(out_codes.unique().tolist()) - set(gen_sequence.unique().tolist())  # set()
        
        # UNIQUE are the SAME ---------------?> is it rearrange
        
        
        
        # ARE SOME PARTS IGNORED OR RE-ARRANGED
        
        # print(f'{unknown_token=} {gen_sequence.shape=}  {out_codes.shape=}')
        # -> unknown tokn = -1 or 2048
        # unknown_token=-1
        
        print(f' <=> CODES {out_codes.shape=} {out_codes.min()}  {out_codes.max()}\n')   # ARRIVES here also if special
        
        # unknown_token=-1 gen_sequence.shape=torch.Size([1, 4, 39])  out_codes.shape=torch.Size([1, 4, 35])
        # <=> CODES out_codes.shape=torch.Size([1, 4, 35]) 30  2024

        
        
        # Clean Transformer MHA k_history v_history
        for lay in self.transformer.layers:
             lay.self_attn.k_history = None
             lay.self_attn.v_history = None
        
        return out_codes  #