llama.py 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  1. import dataclasses
  2. import json
  3. import math
  4. from collections import OrderedDict
  5. from dataclasses import dataclass
  6. from pathlib import Path
  7. from typing import Optional
  8. import torch
  9. import torch.nn as nn
  10. from einops import rearrange
  11. from loguru import logger
  12. from torch import Tensor
  13. from torch.nn import functional as F
  14. from torch.nn.attention import SDPBackend, sdpa_kernel
  15. from torch.utils.checkpoint import checkpoint
  16. from fish_speech.models.text2semantic.lora import LoraConfig, setup_lora
  17. def find_multiple(n: int, k: int) -> int:
  18. if n % k == 0:
  19. return n
  20. return n + k - (n % k)
  21. @dataclass
  22. class BaseModelArgs:
  23. model_type: str = "base"
  24. vocab_size: int = 32000
  25. n_layer: int = 32
  26. n_head: int = 32
  27. dim: int = 4096
  28. intermediate_size: int = None
  29. n_local_heads: int = -1
  30. head_dim: int = 64
  31. rope_base: float = 10000
  32. norm_eps: float = 1e-5
  33. max_seq_len: int = 2048
  34. dropout: float = 0.0
  35. tie_word_embeddings: bool = True
  36. attention_qkv_bias: bool = False
  37. attention_o_bias: bool = False
  38. attention_qk_norm: bool = False
  39. # Codebook configs
  40. codebook_size: int = 160
  41. num_codebooks: int = 4
  42. semantic_begin_id: int = 0
  43. semantic_end_id: int = 0
  44. # Gradient checkpointing
  45. use_gradient_checkpointing: bool = True
  46. # Initialize the model
  47. initializer_range: float = 0.02
  48. # Dummy vars
  49. is_reward_model: bool = False
  50. scale_codebook_embeddings: bool = False
  51. audio_embed_dim: Optional[int] = None
  52. def __post_init__(self):
  53. if self.n_local_heads == -1:
  54. self.n_local_heads = self.n_head
  55. if self.intermediate_size is None:
  56. hidden_dim = 4 * self.dim
  57. n_hidden = int(2 * hidden_dim / 3)
  58. self.intermediate_size = find_multiple(n_hidden, 256)
  59. if self.head_dim is None:
  60. self.head_dim = self.dim // self.n_head
  61. @staticmethod
  62. def from_pretrained(path: str):
  63. path = Path(path)
  64. if path.is_dir():
  65. path = path / "config.json"
  66. with open(path, "r", encoding="utf-8") as f:
  67. data = json.load(f)
  68. match data["model_type"]:
  69. case "naive":
  70. cls = NaiveModelArgs
  71. case "dual_ar":
  72. cls = DualARModelArgs
  73. case "fish_qwen3_omni":
  74. return BaseModelArgs._from_fish_qwen3_omni(data)
  75. case _:
  76. raise ValueError(f"Unknown model type: {data['model_type']}")
  77. # Filter out unexpected keyword arguments
  78. valid_keys = {f.name for f in dataclasses.fields(cls)}
  79. data = {k: v for k, v in data.items() if k in valid_keys}
  80. return cls(**data)
  81. @staticmethod
  82. def _from_fish_qwen3_omni(data: dict) -> "DualARModelArgs":
  83. tc = data["text_config"]
  84. adc = data["audio_decoder_config"]
  85. flat = dict(
  86. model_type="dual_ar",
  87. vocab_size=tc["vocab_size"],
  88. n_layer=tc["n_layer"],
  89. n_head=tc["n_head"],
  90. n_local_heads=tc.get("n_local_heads", -1),
  91. head_dim=tc.get("head_dim"),
  92. dim=tc["dim"],
  93. intermediate_size=tc.get("intermediate_size"),
  94. rope_base=tc.get("rope_base", 10000),
  95. norm_eps=tc.get("norm_eps", 1e-5),
  96. max_seq_len=tc.get("max_seq_len", 2048),
  97. dropout=tc.get("dropout", 0.0),
  98. tie_word_embeddings=tc.get("tie_word_embeddings", True),
  99. attention_qkv_bias=tc.get("attention_qkv_bias", False),
  100. attention_o_bias=tc.get("attention_o_bias", False),
  101. attention_qk_norm=tc.get("attention_qk_norm", False),
  102. use_gradient_checkpointing=tc.get("use_gradient_checkpointing", True),
  103. initializer_range=tc.get("initializer_range", 0.02),
  104. semantic_begin_id=data.get("semantic_start_token_id", 0),
  105. semantic_end_id=data.get("semantic_end_token_id", 0),
  106. scale_codebook_embeddings=True,
  107. norm_fastlayer_input=True,
  108. audio_embed_dim=adc.get("text_dim", tc["dim"]),
  109. codebook_size=adc["vocab_size"],
  110. num_codebooks=adc["num_codebooks"],
  111. n_fast_layer=adc["n_layer"],
  112. fast_dim=adc.get("dim"),
  113. fast_n_head=adc.get("n_head"),
  114. fast_n_local_heads=adc.get("n_local_heads"),
  115. fast_head_dim=adc.get("head_dim"),
  116. fast_intermediate_size=adc.get("intermediate_size"),
  117. fast_attention_qkv_bias=adc.get("attention_qkv_bias"),
  118. fast_attention_qk_norm=adc.get("attention_qk_norm"),
  119. fast_attention_o_bias=adc.get("attention_o_bias"),
  120. )
  121. valid_keys = {f.name for f in dataclasses.fields(DualARModelArgs)}
  122. flat = {k: v for k, v in flat.items() if k in valid_keys and v is not None}
  123. return DualARModelArgs(**flat)
  124. def save(self, path: str):
  125. with open(path, "w") as f:
  126. json.dump(self.__dict__, f, indent=4, sort_keys=True, ensure_ascii=False)
  127. @dataclass
  128. class NaiveModelArgs(BaseModelArgs):
  129. model_type: str = "naive"
  130. @dataclass
  131. class DualARModelArgs(BaseModelArgs):
  132. model_type: str = "dual_ar"
  133. n_fast_layer: int = 4
  134. fast_dim: int | None = None
  135. fast_n_head: int | None = None
  136. fast_n_local_heads: int | None = None
  137. fast_head_dim: int | None = None
  138. fast_intermediate_size: int | None = None
  139. fast_attention_qkv_bias: bool | None = None
  140. fast_attention_qk_norm: bool | None = None
  141. fast_attention_o_bias: bool | None = None
  142. norm_fastlayer_input: bool = False
  143. def __post_init__(self):
  144. super().__post_init__()
  145. self.fast_dim = self.fast_dim or self.dim
  146. self.fast_n_head = self.fast_n_head or self.n_head
  147. self.fast_n_local_heads = self.fast_n_local_heads or self.n_local_heads
  148. self.fast_head_dim = self.fast_head_dim or self.head_dim
  149. self.fast_intermediate_size = (
  150. self.fast_intermediate_size or self.intermediate_size
  151. )
  152. self.fast_attention_qkv_bias = (
  153. self.fast_attention_qkv_bias
  154. if self.fast_attention_qkv_bias is not None
  155. else self.attention_qkv_bias
  156. )
  157. self.fast_attention_qk_norm = (
  158. self.fast_attention_qk_norm
  159. if self.fast_attention_qk_norm is not None
  160. else self.attention_qk_norm
  161. )
  162. self.fast_attention_o_bias = (
  163. self.fast_attention_o_bias
  164. if self.fast_attention_o_bias is not None
  165. else self.attention_o_bias
  166. )
  167. class KVCache(nn.Module):
  168. def __init__(
  169. self, max_batch_size, max_seq_len, n_heads, head_dim, dtype=torch.bfloat16
  170. ):
  171. super().__init__()
  172. logger.info(f"Initializing KVCache max_batch_size={max_batch_size}, max_seq_len={max_seq_len}, n_heads={n_heads}, head_dim={head_dim}")
  173. cache_shape = (max_batch_size, n_heads, max_seq_len, head_dim)
  174. self.register_buffer("k_cache", torch.zeros(cache_shape, dtype=dtype))
  175. self.register_buffer("v_cache", torch.zeros(cache_shape, dtype=dtype))
  176. def update(self, input_pos, k_val, v_val):
  177. # input_pos: [S], k_val: [B, H, S, D]
  178. assert input_pos.shape[0] == k_val.shape[2]
  179. k_out = self.k_cache
  180. v_out = self.v_cache
  181. k_out[:, :, input_pos] = k_val
  182. v_out[:, :, input_pos] = v_val
  183. return k_out, v_out
  184. @dataclass
  185. class TransformerForwardResult:
  186. token_logits: Tensor
  187. codebook_logits: Tensor
  188. @dataclass
  189. class BaseTransformerForwardResult:
  190. logits: Tensor
  191. hidden_states: Tensor
  192. def _remap_fish_qwen3_omni_keys(weights: OrderedDict) -> OrderedDict:
  193. if not any(k.startswith(("text_model.", "audio_decoder.")) for k in weights):
  194. return weights
  195. new_weights = OrderedDict()
  196. for k, v in weights.items():
  197. if k.startswith("text_model.model."):
  198. new_key = k[len("text_model.model.") :]
  199. elif k.startswith("audio_decoder."):
  200. suffix = k[len("audio_decoder.") :]
  201. new_key = (
  202. suffix
  203. if suffix.startswith("codebook_embeddings.")
  204. else "fast_" + suffix
  205. )
  206. else:
  207. new_key = k
  208. new_weights[new_key] = v
  209. return new_weights
  210. class BaseTransformer(nn.Module):
  211. def __init__(
  212. self,
  213. config: BaseModelArgs,
  214. init_weights: bool = True,
  215. ) -> None:
  216. super().__init__()
  217. self.config = config
  218. # Slow transformer
  219. self.embeddings = nn.Embedding(
  220. config.vocab_size,
  221. config.dim,
  222. )
  223. self.codebook_embeddings = nn.Embedding(
  224. config.codebook_size * config.num_codebooks,
  225. config.dim,
  226. )
  227. self.layers = nn.ModuleList(
  228. TransformerBlock(config, use_sdpa=True) for _ in range(config.n_layer)
  229. )
  230. self.norm = RMSNorm(config.dim, eps=config.norm_eps)
  231. if self.config.tie_word_embeddings is False:
  232. self.output = nn.Linear(
  233. config.dim,
  234. config.vocab_size,
  235. bias=False,
  236. )
  237. self.register_buffer(
  238. "freqs_cis",
  239. precompute_freqs_cis(
  240. config.max_seq_len,
  241. config.head_dim,
  242. config.rope_base,
  243. ),
  244. persistent=False,
  245. )
  246. self.register_buffer(
  247. "causal_mask",
  248. torch.tril(
  249. torch.ones(
  250. config.max_seq_len,
  251. config.max_seq_len,
  252. dtype=torch.bool,
  253. )
  254. ),
  255. persistent=False,
  256. )
  257. # For kv cache
  258. self.max_batch_size = -1
  259. self.max_seq_len = -1
  260. if init_weights:
  261. self.apply(self._init_weights)
  262. def setup_caches(
  263. self, max_batch_size: int, max_seq_len: int, dtype: torch.dtype = torch.bfloat16
  264. ):
  265. if self.max_seq_len >= max_seq_len and self.max_batch_size >= max_batch_size:
  266. return
  267. max_seq_len = find_multiple(max_seq_len, 8)
  268. self.max_seq_len = max_seq_len
  269. self.max_batch_size = max_batch_size
  270. for b in self.layers:
  271. b.attention.kv_cache = KVCache(
  272. max_batch_size,
  273. max_seq_len,
  274. self.config.n_local_heads,
  275. self.config.head_dim,
  276. dtype=dtype,
  277. )
  278. def embed(self, inp: Tensor) -> Tensor:
  279. embeds = []
  280. for i in range(self.config.num_codebooks):
  281. emb = self.codebook_embeddings(
  282. inp[:, i + 1] + i * self.config.codebook_size
  283. )
  284. embeds.append(emb)
  285. vq_embeds_sum = torch.stack(embeds, dim=1).sum(dim=1)
  286. is_semantic = (inp[:, 0] >= self.config.semantic_begin_id) & (
  287. inp[:, 0] <= self.config.semantic_end_id
  288. )
  289. vq_embeds_sum[~is_semantic] = 0
  290. x = self.embeddings(inp[:, 0]) + vq_embeds_sum
  291. return x
  292. def forward(
  293. self,
  294. inp: Tensor,
  295. key_padding_mask: Optional[Tensor] = None,
  296. ) -> BaseTransformerForwardResult:
  297. seq_len = inp.size(2)
  298. # Here we want to merge the embeddings of the codebooks
  299. x = self.embed(inp)
  300. freqs_cis = self.freqs_cis[:seq_len]
  301. mask = None
  302. if key_padding_mask is not None:
  303. causal = self.causal_mask[:seq_len, :seq_len]
  304. causal = rearrange(causal, "q k -> 1 1 q k")
  305. atten_mask = rearrange(key_padding_mask, "b s -> b 1 1 s")
  306. atten_mask = atten_mask.logical_not()
  307. mask = causal & atten_mask
  308. for layer in self.layers:
  309. if self.config.use_gradient_checkpointing and self.training:
  310. x = checkpoint(layer, x, freqs_cis, mask, use_reentrant=True)
  311. else:
  312. x = layer(x, freqs_cis, mask)
  313. slow_out = self.norm(x)
  314. if self.config.tie_word_embeddings:
  315. token_logits = F.linear(slow_out, self.embeddings.weight)
  316. else:
  317. token_logits = self.output(slow_out)
  318. hidden_out = (
  319. slow_out if getattr(self.config, "norm_fastlayer_input", False) else x
  320. )
  321. return BaseTransformerForwardResult(
  322. logits=token_logits,
  323. hidden_states=hidden_out,
  324. )
  325. def forward_generate(
  326. self,
  327. inp: Tensor,
  328. input_pos: Optional[Tensor] = None,
  329. audio_masks: Optional[Tensor] = None,
  330. audio_parts: Optional[Tensor] = None,
  331. return_all: bool = False,
  332. ) -> BaseTransformerForwardResult:
  333. # Embedding logic replicated from embed() for compilation compatibility
  334. embeds = []
  335. for i in range(self.config.num_codebooks):
  336. emb = self.codebook_embeddings(
  337. inp[:, i + 1] + i * self.config.codebook_size
  338. )
  339. embeds.append(emb)
  340. vq_embeds_sum = torch.stack(embeds, dim=1).sum(dim=1)
  341. vq_masks = (inp[:, 0] >= self.config.semantic_begin_id) & (
  342. inp[:, 0] <= self.config.semantic_end_id
  343. )
  344. vq_embeds_sum[~vq_masks] = 0
  345. x = self.embeddings(inp[:, 0]) + vq_embeds_sum
  346. if self.config.scale_codebook_embeddings:
  347. vq_masks_expanded = vq_masks.unsqueeze(-1).expand_as(x)
  348. x = torch.where(
  349. vq_masks_expanded, x / math.sqrt(self.config.num_codebooks + 1), x
  350. )
  351. # Audio embeddings
  352. if audio_parts is not None:
  353. # Note: This assumes self.audio_projector exists if audio_parts is used
  354. # It seems missing in init, but we keep existing logic
  355. if hasattr(self, "audio_projector"):
  356. audio_embeds = self.audio_projector(audio_parts)
  357. if self.config.scale_codebook_embeddings:
  358. x[audio_masks] = audio_embeds / math.sqrt(2)
  359. else:
  360. x[audio_masks] = audio_embeds
  361. else:
  362. logger.warning("audio_parts provided but model has no audio_projector")
  363. if input_pos is None:
  364. input_pos = torch.arange(inp.shape[-1], device=x.device)
  365. max_seq_len = inp.shape[-1]
  366. else:
  367. max_seq_len = self.max_seq_len
  368. mask = self.causal_mask[None, None, input_pos, :max_seq_len] # (B, N, Q, K)
  369. freqs_cis = self.freqs_cis[input_pos]
  370. for layer in self.layers:
  371. x = layer(x, freqs_cis, mask, input_pos=input_pos)
  372. if x.size(1) > 1 and not return_all:
  373. x = x[:, -1:]
  374. slow_out = self.norm(x)
  375. if self.config.is_reward_model:
  376. token_logits = self.score_output(slow_out)
  377. elif self.config.tie_word_embeddings:
  378. token_logits = F.linear(slow_out, self.embeddings.weight)
  379. else:
  380. token_logits = self.output(slow_out)
  381. hidden_out = (
  382. slow_out if getattr(self.config, "norm_fastlayer_input", False) else x
  383. )
  384. return BaseTransformerForwardResult(
  385. logits=token_logits,
  386. hidden_states=hidden_out,
  387. )
  388. def _init_weights(self, module):
  389. std = self.config.initializer_range
  390. if isinstance(module, nn.Linear):
  391. module.weight.data.normal_(mean=0.0, std=std)
  392. if module.bias is not None:
  393. module.bias.data.zero_()
  394. elif isinstance(module, nn.Embedding):
  395. module.weight.data.normal_(mean=0.0, std=std)
  396. if module.padding_idx is not None:
  397. module.weight.data[module.padding_idx].zero_()
  398. @staticmethod
  399. def from_pretrained(
  400. path: str,
  401. load_weights: bool = False,
  402. max_length: int | None = None,
  403. lora_config: LoraConfig | None = None,
  404. rope_base: int | None = None,
  405. ) -> "BaseTransformer":
  406. # Import wrapper locally to avoid circular dependency or global import issues
  407. from fish_speech.tokenizer import FishTokenizer
  408. config = BaseModelArgs.from_pretrained(str(path))
  409. if max_length is not None:
  410. config.max_seq_len = max_length
  411. logger.info(f"Override max_seq_len to {max_length}")
  412. if rope_base is not None:
  413. config.rope_base = rope_base
  414. logger.info(f"Override rope_base to {rope_base}")
  415. tokenizer = None
  416. try:
  417. tokenizer = FishTokenizer.from_pretrained(path)
  418. config.semantic_begin_id = tokenizer.semantic_begin_id
  419. config.semantic_end_id = tokenizer.semantic_end_id
  420. logger.info(
  421. f"Injected Semantic IDs into Config: {config.semantic_begin_id}-{config.semantic_end_id}"
  422. )
  423. except Exception as e:
  424. logger.warning(
  425. f"Failed to load tokenizer for config injection: {e}. Semantic IDs might be 0."
  426. )
  427. match config.model_type:
  428. case "naive":
  429. model_cls = NaiveTransformer
  430. case "dual_ar":
  431. model_cls = DualARTransformer
  432. case _:
  433. raise ValueError(f"Unknown model type: {config.model_type}")
  434. logger.info(f"Loading model from {path}, config: {config}")
  435. # Initialize model without passing tokenizer explicitly to __init__
  436. model = model_cls(config)
  437. # Attach tokenizer to model instance for inference convenience (optional, but good for user scripts)
  438. model.tokenizer = tokenizer
  439. if load_weights is False:
  440. logger.info("Randomly initialized model")
  441. else:
  442. if "int8" in str(Path(path)):
  443. logger.info("Using int8 weight-only quantization!")
  444. from tools.llama.quantize import WeightOnlyInt8QuantHandler
  445. simple_quantizer = WeightOnlyInt8QuantHandler(model)
  446. model = simple_quantizer.convert_for_runtime()
  447. if "int4" in str(Path(path)):
  448. logger.info("Using int4 quantization!")
  449. path_comps = path.name.split("-")
  450. assert path_comps[-2].startswith("g")
  451. groupsize = int(path_comps[-2][1:])
  452. from tools.llama.quantize import WeightOnlyInt4QuantHandler
  453. simple_quantizer = WeightOnlyInt4QuantHandler(model, groupsize)
  454. model = simple_quantizer.convert_for_runtime()
  455. path_obj = Path(path)
  456. index_json = path_obj / "model.safetensors.index.json"
  457. single_st = path_obj / "model.safetensors"
  458. pth_file = path_obj / "model.pth"
  459. if index_json.exists():
  460. logger.info("Loading sharded safetensors weights")
  461. from safetensors.torch import load_file as st_load_file
  462. with open(index_json) as f:
  463. st_index = json.load(f)
  464. shard_files = sorted(set(st_index["weight_map"].values()))
  465. weights = OrderedDict()
  466. for shard in shard_files:
  467. weights.update(st_load_file(str(path_obj / shard), device="cpu"))
  468. weights = _remap_fish_qwen3_omni_keys(weights)
  469. elif single_st.exists():
  470. logger.info("Loading single safetensors weights")
  471. from safetensors.torch import load_file as st_load_file
  472. weights = OrderedDict(st_load_file(str(single_st), device="cpu"))
  473. weights = _remap_fish_qwen3_omni_keys(weights)
  474. elif pth_file.exists():
  475. weights = torch.load(
  476. pth_file,
  477. map_location="cpu",
  478. mmap=True,
  479. weights_only=True,
  480. )
  481. if "state_dict" in weights:
  482. weights = weights["state_dict"]
  483. if weights and next(iter(weights.keys())).startswith("model."):
  484. weights = OrderedDict(
  485. (k.replace("model.", ""), v) for k, v in weights.items()
  486. )
  487. for k in list(weights.keys()):
  488. if "audio_" in k:
  489. weights.pop(k)
  490. else:
  491. raise FileNotFoundError(f"No model weights found in {path_obj}")
  492. err = model.load_state_dict(weights, strict=False, assign=True)
  493. logger.info(f"Model weights loaded - Status: {err}")
  494. if lora_config is not None:
  495. setup_lora(model, lora_config)
  496. logger.info(f"LoRA setup: {lora_config}")
  497. return model
  498. def save_pretrained(self, path: str, drop_lora: bool = False):
  499. path = Path(path)
  500. path.mkdir(parents=True, exist_ok=True)
  501. self.config.save(path / "config.json")
  502. state_dict = self.state_dict()
  503. if drop_lora:
  504. for key in list(state_dict.keys()):
  505. if "lora" not in key:
  506. continue
  507. state_dict.pop(key)
  508. torch.save(state_dict, path / "model.pth")
  509. if hasattr(self, "tokenizer"):
  510. self.tokenizer.save_pretrained(path)
  511. class NaiveTransformer(BaseTransformer):
  512. def __init__(self, config: NaiveModelArgs) -> None:
  513. super().__init__(config, init_weights=False)
  514. self.codebook_norm = RMSNorm(config.dim, eps=config.norm_eps)
  515. self.codebook_output = nn.Linear(
  516. config.dim,
  517. config.codebook_size * config.num_codebooks,
  518. bias=False,
  519. )
  520. self.apply(self._init_weights)
  521. def decode(self, result: BaseTransformerForwardResult) -> TransformerForwardResult:
  522. token_logits = result.logits
  523. x = result.hidden_states
  524. # Codebook
  525. codebook_logits = self.codebook_output(self.codebook_norm(x))
  526. codebook_logits = rearrange(
  527. codebook_logits, "b n (c d) -> b n c d", c=self.config.num_codebooks
  528. )
  529. return TransformerForwardResult(
  530. token_logits=token_logits,
  531. codebook_logits=codebook_logits,
  532. )
  533. def forward(
  534. self,
  535. inp: Tensor,
  536. key_padding_mask: Optional[Tensor] = None,
  537. ) -> TransformerForwardResult:
  538. result = super().forward(
  539. inp=inp,
  540. key_padding_mask=key_padding_mask,
  541. )
  542. return self.decode(result)
  543. def forward_generate(
  544. self, x: Tensor, input_pos: Optional[Tensor] = None
  545. ) -> TransformerForwardResult:
  546. result = super().forward_generate(x, input_pos)
  547. return self.decode(result)
  548. class DualARTransformer(BaseTransformer):
  549. def __init__(self, config: NaiveModelArgs) -> None:
  550. super().__init__(config, init_weights=False)
  551. # Project to fast dim if needed
  552. if config.fast_dim is not None and config.fast_dim != config.dim:
  553. self.fast_project_in = nn.Linear(config.dim, config.fast_dim)
  554. else:
  555. self.fast_project_in = nn.Identity()
  556. # Fast transformer
  557. self.fast_embeddings = nn.Embedding(config.codebook_size, config.fast_dim)
  558. # The equivalent bs is so large that sdpa doesn't work
  559. override_config = dataclasses.replace(
  560. config,
  561. dim=config.fast_dim,
  562. n_head=config.fast_n_head,
  563. n_local_heads=config.fast_n_local_heads,
  564. head_dim=config.fast_head_dim,
  565. intermediate_size=config.fast_intermediate_size,
  566. attention_qkv_bias=config.fast_attention_qkv_bias,
  567. attention_qk_norm=config.fast_attention_qk_norm,
  568. attention_o_bias=config.fast_attention_o_bias,
  569. )
  570. self.fast_layers = nn.ModuleList(
  571. TransformerBlock(override_config, use_sdpa=False)
  572. for _ in range(config.n_fast_layer)
  573. )
  574. self.fast_norm = RMSNorm(config.fast_dim, eps=config.norm_eps)
  575. self.fast_output = nn.Linear(
  576. config.fast_dim,
  577. config.codebook_size,
  578. bias=False,
  579. )
  580. self.register_buffer(
  581. "fast_freqs_cis",
  582. precompute_freqs_cis(
  583. config.num_codebooks,
  584. config.fast_head_dim,
  585. config.rope_base,
  586. ),
  587. persistent=False,
  588. )
  589. self.apply(self._init_weights)
  590. def setup_caches(
  591. self, max_batch_size: int, max_seq_len: int, dtype: torch.dtype = torch.bfloat16
  592. ):
  593. super().setup_caches(max_batch_size, max_seq_len, dtype)
  594. # Fast transformer
  595. # The max seq len here is the number of codebooks
  596. for b in self.fast_layers:
  597. b.attention.kv_cache = KVCache(
  598. max_batch_size,
  599. self.config.num_codebooks,
  600. self.config.fast_n_local_heads,
  601. self.config.fast_head_dim,
  602. dtype=dtype,
  603. )
  604. def forward(
  605. self,
  606. inp: Tensor,
  607. labels: Optional[Tensor] = None,
  608. key_padding_mask: Optional[Tensor] = None,
  609. vq_parts: Optional[Tensor] = None,
  610. vq_masks: Optional[Tensor] = None,
  611. vq_require_losses: Optional[Tensor] = None,
  612. mel_parts: Optional[Tensor] = None,
  613. mel_masks: Optional[Tensor] = None,
  614. ) -> TransformerForwardResult:
  615. parent_result = super().forward(
  616. inp=inp,
  617. key_padding_mask=key_padding_mask,
  618. )
  619. token_logits = parent_result.logits
  620. x = parent_result.hidden_states
  621. # Fast transformer
  622. fast_seq_len = self.config.num_codebooks
  623. fast_mask = self.causal_mask[
  624. None, None, :fast_seq_len, :fast_seq_len
  625. ] # (B, N, Q, K)
  626. fast_freqs_cis = self.fast_freqs_cis[:fast_seq_len]
  627. # Extract corresponding parts with labels
  628. token_labels = labels[:, 0]
  629. # [MODIFIED] Use config instead of tokenizer
  630. codebook_mask = (token_labels >= self.config.semantic_begin_id) & (
  631. token_labels <= self.config.semantic_end_id
  632. )
  633. # This gives where input token is <|semantic|>
  634. x = x[codebook_mask]
  635. if x.shape[0] == 0:
  636. # Use dummy input when no vq is required
  637. x = torch.zeros(
  638. (4, self.config.dim),
  639. device=x.device,
  640. dtype=x.dtype,
  641. )
  642. codebooks = torch.zeros(
  643. (x.shape[0], self.config.num_codebooks - 1),
  644. device=x.device,
  645. dtype=torch.int,
  646. )
  647. else:
  648. all_codebooks = labels[:, 1:, :]
  649. all_codebooks_permuted = all_codebooks.permute(0, 2, 1)
  650. semantic_codebooks = all_codebooks_permuted[codebook_mask]
  651. codebooks = semantic_codebooks[:, :-1]
  652. x = self.fast_project_in(x)
  653. codebook_embeddings = self.fast_embeddings(codebooks)
  654. x = torch.cat([x[:, None], codebook_embeddings], dim=1)
  655. for layer in self.fast_layers:
  656. if self.config.use_gradient_checkpointing and self.training:
  657. x = checkpoint(layer, x, fast_freqs_cis, fast_mask, use_reentrant=True)
  658. else:
  659. x = layer(x, fast_freqs_cis, fast_mask)
  660. # unflatten the batch and num_codebooks
  661. fast_out = self.fast_norm(x)
  662. codebook_logits = self.fast_output(fast_out)
  663. assert codebook_logits.shape[1] == self.config.num_codebooks
  664. return TransformerForwardResult(
  665. token_logits=token_logits,
  666. codebook_logits=codebook_logits,
  667. )
  668. def forward_generate_fast(
  669. self, x: Tensor, input_pos: Optional[Tensor] = None
  670. ) -> Tensor:
  671. # Fast transformer
  672. x = x.view(x.shape[0], 1, -1)
  673. fast_mask = self.causal_mask[
  674. None, None, input_pos, : self.config.num_codebooks
  675. ] # (B, N, Q, K)
  676. fast_freqs_cis = self.fast_freqs_cis[input_pos]
  677. for layer in self.fast_layers:
  678. x = layer(x, fast_freqs_cis, fast_mask, input_pos=input_pos)
  679. # unflatten the batch and num_codebooks
  680. fast_out = self.fast_norm(x) # only take the last token
  681. codebook_logits = self.fast_output(fast_out)
  682. return codebook_logits
  683. def forward_generate(
  684. self,
  685. x: Tensor,
  686. input_pos: Optional[Tensor] = None,
  687. audio_masks: Optional[Tensor] = None,
  688. audio_parts: Optional[Tensor] = None,
  689. ) -> TransformerForwardResult:
  690. x = super().forward_generate(x, input_pos, audio_masks, audio_parts)
  691. x.hidden_states = self.fast_project_in(x.hidden_states)
  692. return x
  693. class TransformerBlock(nn.Module):
  694. def __init__(self, config: BaseModelArgs, use_sdpa: bool = True) -> None:
  695. super().__init__()
  696. self.attention = Attention(config, use_sdpa=use_sdpa)
  697. self.feed_forward = FeedForward(config)
  698. self.ffn_norm = RMSNorm(config.dim, config.norm_eps)
  699. self.attention_norm = RMSNorm(config.dim, config.norm_eps)
  700. def forward(
  701. self, x: Tensor, freqs_cis: Tensor, mask: Tensor, input_pos: Tensor = None
  702. ) -> Tensor:
  703. h = x + self.attention(self.attention_norm(x), freqs_cis, mask, input_pos)
  704. out = h + self.feed_forward(self.ffn_norm(h))
  705. return out
  706. class Attention(nn.Module):
  707. def __init__(self, config: BaseModelArgs, use_sdpa: bool = True):
  708. super().__init__()
  709. assert config.dim % config.n_head == 0
  710. total_head_dim = (config.n_head + 2 * config.n_local_heads) * config.head_dim
  711. # key, query, value projections for all heads, but in a batch
  712. self.wqkv = nn.Linear(
  713. config.dim, total_head_dim, bias=config.attention_qkv_bias
  714. )
  715. self.wo = nn.Linear(
  716. config.n_head * config.head_dim, config.dim, bias=config.attention_o_bias
  717. )
  718. self.kv_cache = None
  719. if config.attention_qk_norm:
  720. self.q_norm = nn.RMSNorm(config.head_dim, config.norm_eps)
  721. self.k_norm = nn.RMSNorm(config.head_dim, config.norm_eps)
  722. self.dropout = config.dropout
  723. self.n_head = config.n_head
  724. self.head_dim = config.head_dim
  725. self.n_local_heads = config.n_local_heads
  726. self.dim = config.dim
  727. self.use_sdpa = use_sdpa
  728. self.attention_qk_norm = config.attention_qk_norm
  729. self.config = config
  730. self._register_load_state_dict_pre_hook(self.load_hook)
  731. def load_hook(self, state_dict, prefix, *args):
  732. if prefix + "wq.weight" in state_dict:
  733. wq = state_dict.pop(prefix + "wq.weight")
  734. wk = state_dict.pop(prefix + "wk.weight")
  735. wv = state_dict.pop(prefix + "wv.weight")
  736. state_dict[prefix + "wqkv.weight"] = torch.cat([wq, wk, wv])
  737. def forward(
  738. self,
  739. x: Tensor,
  740. freqs_cis: Tensor,
  741. mask: Tensor,
  742. input_pos: Optional[Tensor] = None,
  743. ) -> Tensor:
  744. bsz, seqlen, _ = x.shape
  745. q_size = self.n_head * self.head_dim
  746. kv_size = self.n_local_heads * self.head_dim
  747. q, k, v = self.wqkv(x).split([q_size, kv_size, kv_size], dim=-1)
  748. q = q.view(bsz, seqlen, self.n_head, self.head_dim)
  749. k = k.view(bsz, seqlen, self.n_local_heads, self.head_dim)
  750. v = v.view(bsz, seqlen, self.n_local_heads, self.head_dim)
  751. if self.attention_qk_norm:
  752. q = self.q_norm(q)
  753. k = self.k_norm(k)
  754. q = apply_rotary_emb(q, freqs_cis)
  755. k = apply_rotary_emb(k, freqs_cis)
  756. q, k, v = map(lambda x: x.transpose(1, 2), (q, k, v))
  757. if self.kv_cache is not None:
  758. k, v = self.kv_cache.update(input_pos, k, v)
  759. k = k.repeat_interleave(self.n_head // self.n_local_heads, dim=1)
  760. v = v.repeat_interleave(self.n_head // self.n_local_heads, dim=1)
  761. if self.use_sdpa:
  762. if mask is None:
  763. with sdpa_kernel(SDPBackend.FLASH_ATTENTION):
  764. y = F.scaled_dot_product_attention(
  765. q,
  766. k,
  767. v,
  768. dropout_p=self.dropout if self.training else 0.0,
  769. is_causal=True,
  770. # No third party attn_mask here to use flash_attention
  771. )
  772. else:
  773. y = F.scaled_dot_product_attention(
  774. q,
  775. k,
  776. v,
  777. attn_mask=mask,
  778. dropout_p=self.dropout if self.training else 0.0,
  779. )
  780. else:
  781. y = self.eq_scaled_dot_product_attention(
  782. q,
  783. k,
  784. v,
  785. attn_mask=mask,
  786. dropout_p=self.dropout if self.training else 0.0,
  787. )
  788. y = y.transpose(1, 2).contiguous().view(bsz, seqlen, q_size)
  789. return self.wo(y)
  790. def eq_scaled_dot_product_attention(
  791. self,
  792. query,
  793. key,
  794. value,
  795. attn_mask=None,
  796. dropout_p=0.0,
  797. ) -> torch.Tensor:
  798. # This is a standard scaled dot product attention
  799. # It's low efficient, but it doesn't raise cuda error
  800. L, S = query.size(-2), key.size(-2)
  801. scale_factor = 1 / math.sqrt(query.size(-1))
  802. attn_bias = torch.zeros(1, 1, L, S, dtype=query.dtype, device=query.device)
  803. if attn_mask is not None:
  804. if attn_mask.dtype == torch.bool:
  805. attn_bias = torch.where(
  806. attn_mask.logical_not(), float("-inf"), attn_bias
  807. )
  808. else:
  809. attn_bias = attn_bias + attn_mask
  810. attn_weight = query @ key.transpose(-2, -1) * scale_factor
  811. attn_weight += attn_bias
  812. attn_weight = torch.softmax(attn_weight, dim=-1)
  813. attn_weight = torch.dropout(attn_weight, dropout_p, train=True)
  814. return attn_weight @ value
  815. class FeedForward(nn.Module):
  816. def __init__(self, config: BaseModelArgs) -> None:
  817. super().__init__()
  818. self.w1 = nn.Linear(config.dim, config.intermediate_size, bias=False)
  819. self.w3 = nn.Linear(config.dim, config.intermediate_size, bias=False)
  820. self.w2 = nn.Linear(config.intermediate_size, config.dim, bias=False)
  821. def forward(self, x: Tensor) -> Tensor:
  822. return self.w2(F.silu(self.w1(x)) * self.w3(x))
  823. class RMSNorm(nn.Module):
  824. def __init__(self, dim: int, eps: float = 1e-5):
  825. super().__init__()
  826. self.eps = eps
  827. self.weight = nn.Parameter(torch.ones(dim))
  828. def _norm(self, x):
  829. return x * torch.rsqrt(torch.mean(x * x, dim=-1, keepdim=True) + self.eps)
  830. def forward(self, x: Tensor) -> Tensor:
  831. output = self._norm(x.float()).type_as(x)
  832. return output * self.weight
  833. def precompute_freqs_cis(seq_len: int, n_elem: int, base: int = 10000) -> Tensor:
  834. """
  835. Precomputes frequency tensors for complex exponentials (cis)
  836. Args:
  837. seq_len: Length of the sequence for which positional embeddings are needed.
  838. n_elem: Number of elements in the frequency tensor.
  839. base: Base value for the frequency scaling (default: 10000).
  840. Returns:
  841. A tensor containing the precomputed frequencies in real and imaginary parts (bfloat16).
  842. """
  843. freqs = 1.0 / (
  844. base ** (torch.arange(0, n_elem, 2)[: (n_elem // 2)].float() / n_elem)
  845. )
  846. t = torch.arange(seq_len, device=freqs.device)
  847. freqs = torch.outer(t, freqs)
  848. freqs_cis = torch.polar(torch.ones_like(freqs), freqs)
  849. cache = torch.stack([freqs_cis.real, freqs_cis.imag], dim=-1)
  850. return cache.to(dtype=torch.bfloat16)
  851. def apply_rotary_emb(x: Tensor, freqs_cis: Tensor) -> Tensor:
  852. xshaped = x.float().reshape(*x.shape[:-1], -1, 2)
  853. freqs_cis = freqs_cis.view(1, xshaped.size(1), 1, xshaped.size(3), 2)
  854. x_out2 = torch.stack(
  855. [
  856. xshaped[..., 0] * freqs_cis[..., 0] - xshaped[..., 1] * freqs_cis[..., 1],
  857. xshaped[..., 1] * freqs_cis[..., 0] + xshaped[..., 0] * freqs_cis[..., 1],
  858. ],
  859. -1,
  860. )
  861. x_out2 = x_out2.flatten(3)
  862. return x_out2.type_as(x)