Dionyssos's picture
revert transformer.py
2e6c69d
raw
history blame
17.5 kB
from dataclasses import dataclass, field
from itertools import chain
import logging
import math
import re
import typing as tp
import torch
import torch.nn.functional as F
from audiocraft.streaming import StreamingModule
from audiocraft.transformer import StreamingTransformer, create_norm_fn
from dataclasses import dataclass
from functools import partial
from torch import nn
from audiocraft.utils import utils
from audiocraft.activations import get_activation_fn
# ============================================== 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(StreamingModule):
"""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 = 24
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'])
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 = create_norm_fn(norm, dim)
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,
conditions,
condition_tensors=None,
stage = -1):
B, K, S = sequence.shape
input_ = sum([self.emb[k](sequence[:, k]) for k in range(K)])
input_, cross_attention_input = self.fuser(input_, condition_tensors) # DEFINE conditioners.py
# print(f'{input_.shape=} {cross_attention_input.shape=} FUSER LLM FORw')
# input_.shape=torch.Size([1, 1, 1536]) cross_attention_input.shape=torch.Size([2, 7, 1536]) FUSER LLM FORw
out = self.transformer(input_, cross_attention_src=cross_attention_input,
src_mask=(self.attn_mask_per_stage[stage] if stage >= 0 else None))
if self.out_norm:
out = self.out_norm(out)
logits = torch.stack([self.linears[k](out) for k in range(K)], dim=1) # [B, K, S, card]
# 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]
def _sample_next_token(self,
sequence,
cfg_conditions,
unconditional_state):
"""self.n_draw"""
B = sequence.shape[0]
model = self if self._fsdp is None else self._fsdp
condition_tensors = cfg_conditions
# logits = [2, 4, 1, 2048]
logits = model(
sequence, # cond_logits = wav condition
conditions=[], condition_tensors=condition_tensors) # uncond_logits already see the text
# use cfg
# logits = (3 * logits[1, :, :, :] - 2.4 * logits[0, :, :, :]).transpose(1,0)
# or use 1 of logits
logits = logits[0, :, :, :].transpose(1,0) # [2,4,1, 2048] -> [1,4,2048]
# print(f'{B=}, {logits.shape=} SAMPLER {top_k=}')
next_token = utils.sample_top_k(logits, n_draw=self.n_draw) # [1,4,2048] logits
return next_token
# GENERATE class revert_codebook_patterns()
@torch.no_grad()
def generate(self,
prompt = None,
conditions = [],
num_samples = 1, # THIS IS HOW MANY GENERATIONS - A SAMPLE IS A FULL WAV
max_gen_len=256, # unduplicated sequence length - actual len will be n_draw * maxgenlen
use_sampling: bool = True,
**kwargs):
print(f'{num_samples=}')
first_param = next(iter(self.parameters()))
device = first_param.device
# below we create set of conditions: one conditional and one unconditional
# to do that we merge the regular condition together with the null condition
# we then do 1 forward pass instead of 2.
# the reason for that is two-fold:
# 1. it is about x2 faster than doing 2 forward passes
# 2. avoid the streaming API treating the 2 passes as part of different time steps
# We also support doing two different passes, in particular to ensure that
# the padding structure is exactly the same between train and test.
# With a batch size of 1, this can be slower though.
cfg_conditions: CFGConditions
# two_step_cfg = self.two_step_cfg if two_step_cfg is None else two_step_cfg
null_conditions = conditions
conditions = conditions + null_conditions
tokenized = self.condition_provider.tokenize(conditions)
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)
with self.streaming():
unconditional_state = self.get_streaming_state()
prev_offset = 0
gen_sequence_len = _gen_sequence.shape[-1] # gen_sequence shape is [B, K, S]
# --
# print(mask.shape, mask.sum(), 'MSK LM')
# torch.Size([4, 39]) tensor(140, device='cuda:0') MSK LM ? Fully 1 normal no special token
# --
duplicate_draw = [
_gen_sequence[:, :, 0:1].repeat(self.n_draw, 1, 1)
]
# list to hold next tokens - draw sample multiple tokens at each time-step
# but continue the sequence only with isingle next token
for offset in range(1, gen_sequence_len): # start_offset_sequence=1
# print(f'{_gen_sequence.shape=}') # [1,4,16]
# starts from 1 not 0 thus uses the 0:1 as curr sequence
# although this is empty contains -1 ?
curr_sequence = _gen_sequence[..., prev_offset:offset]
next_token = self._sample_next_token(
curr_sequence,
cfg_conditions,
unconditional_state) # [5, 4, 1]
# RUNS with = 2047 just different of self.special_token_id = 2047 = alwayssingletoken = drill noise
# special_token_id is filler for CODEBOOK_PATTERN ?
# next_token[:] = self.special_token_id # seanet.embed torch.embedding does not have this - out of bounds in detokenize
_gen_sequence[..., offset:offset+1] = next_token[0, :, :] #gen_sequence.shape=torch.Size([1, 4, 39])
duplicate_draw.append(next_token)
prev_offset = offset
unconditional_state.clear()
gen_sequence = torch.cat(duplicate_draw, 2) # [self.n_draw, 4, len_seq]
# 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
return out_codes # supposedly contains extra prompt