facebookresearch--audiocraft
1325 行
76 KiB
HTML
1325 行
76 KiB
HTML
<!doctype html>
|
||
<html lang="en">
|
||
<head>
|
||
<meta charset="utf-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
|
||
<meta name="generator" content="pdoc3 0.11.5">
|
||
<title>audiocraft.models.lm API documentation</title>
|
||
<meta name="description" content="">
|
||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
|
||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
|
||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
|
||
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source > summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible;min-width:max-content}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin:1em 0}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
|
||
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
|
||
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
|
||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
|
||
<script>window.addEventListener('DOMContentLoaded', () => {
|
||
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
|
||
hljs.highlightAll();
|
||
/* Collapse source docstrings */
|
||
setTimeout(() => {
|
||
[...document.querySelectorAll('.hljs.language-python > .hljs-string')]
|
||
.filter(el => el.innerHTML.length > 200 && ['"""', "'''"].includes(el.innerHTML.substring(0, 3)))
|
||
.forEach(el => {
|
||
let d = document.createElement('details');
|
||
d.classList.add('hljs-string');
|
||
d.innerHTML = '<summary>"""</summary>' + el.innerHTML.substring(3);
|
||
el.replaceWith(d);
|
||
});
|
||
}, 100);
|
||
})</script>
|
||
</head>
|
||
<body>
|
||
<main>
|
||
<article id="content">
|
||
<header>
|
||
<h1 class="title">Module <code>audiocraft.models.lm</code></h1>
|
||
</header>
|
||
<section id="section-intro">
|
||
</section>
|
||
<section>
|
||
</section>
|
||
<section>
|
||
</section>
|
||
<section>
|
||
<h2 class="section-title" id="header-functions">Functions</h2>
|
||
<dl>
|
||
<dt id="audiocraft.models.lm.get_init_fn"><code class="name flex">
|
||
<span>def <span class="ident">get_init_fn</span></span>(<span>method: str, input_dim: int, init_depth: int | None = None)</span>
|
||
</code></dt>
|
||
<dd>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">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")</code></pre>
|
||
</details>
|
||
<div class="desc"><p>LM layer initialization.
|
||
Inspired from xlformers: <a href="https://github.com/fairinternal/xlformers">https://github.com/fairinternal/xlformers</a></p>
|
||
<h2 id="args">Args</h2>
|
||
<dl>
|
||
<dt><strong><code>method</code></strong> : <code>str</code></dt>
|
||
<dd>Method name for init function. Valid options are:
|
||
'gaussian', 'uniform'.</dd>
|
||
<dt><strong><code>input_dim</code></strong> : <code>int</code></dt>
|
||
<dd>Input dimension of the initialized module.</dd>
|
||
<dt><strong><code>init_depth</code></strong> : <code>int</code>, optional</dt>
|
||
<dd>Optional init depth value used to rescale
|
||
the standard deviation if defined.</dd>
|
||
</dl></div>
|
||
</dd>
|
||
<dt id="audiocraft.models.lm.init_layer"><code class="name flex">
|
||
<span>def <span class="ident">init_layer</span></span>(<span>m: torch.nn.modules.module.Module,<br>method: str,<br>init_depth: int | None = None,<br>zero_bias_init: bool = False)</span>
|
||
</code></dt>
|
||
<dd>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">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)</code></pre>
|
||
</details>
|
||
<div class="desc"><p>Wrapper around <code><a title="audiocraft.models.lm.get_init_fn" href="#audiocraft.models.lm.get_init_fn">get_init_fn()</a></code> for proper initialization of LM modules.</p>
|
||
<h2 id="args">Args</h2>
|
||
<dl>
|
||
<dt><strong><code>m</code></strong> : <code>nn.Module</code></dt>
|
||
<dd>Module to initialize.</dd>
|
||
<dt><strong><code>method</code></strong> : <code>str</code></dt>
|
||
<dd>Method name for the init function.</dd>
|
||
<dt><strong><code>init_depth</code></strong> : <code>int</code>, optional</dt>
|
||
<dd>Optional init depth value used to rescale
|
||
the standard deviation if defined.</dd>
|
||
<dt><strong><code>zero_bias_init</code></strong> : <code>bool</code></dt>
|
||
<dd>Whether to initialize the bias to 0 or not.</dd>
|
||
</dl></div>
|
||
</dd>
|
||
</dl>
|
||
</section>
|
||
<section>
|
||
<h2 class="section-title" id="header-classes">Classes</h2>
|
||
<dl>
|
||
<dt id="audiocraft.models.lm.LMModel"><code class="flex name class">
|
||
<span>class <span class="ident">LMModel</span></span>
|
||
<span>(</span><span>pattern_provider: <a title="audiocraft.modules.codebooks_patterns.CodebooksPatternProvider" href="../modules/codebooks_patterns.html#audiocraft.modules.codebooks_patterns.CodebooksPatternProvider">CodebooksPatternProvider</a>,<br>condition_provider: <a title="audiocraft.modules.conditioners.ConditioningProvider" href="../modules/conditioners.html#audiocraft.modules.conditioners.ConditioningProvider">ConditioningProvider</a>,<br>fuser: <a title="audiocraft.modules.conditioners.ConditionFuser" href="../modules/conditioners.html#audiocraft.modules.conditioners.ConditionFuser">ConditionFuser</a>,<br>n_q: int = 8,<br>card: int = 1024,<br>dim: int = 128,<br>num_heads: int = 8,<br>hidden_scale: int = 4,<br>norm: str = 'layer_norm',<br>norm_first: bool = False,<br>emb_lr: float | None = None,<br>bias_proj: bool = True,<br>weight_init: str | None = None,<br>depthwise_init: str | None = None,<br>zero_bias_init: bool = False,<br>cfg_dropout: float = 0,<br>cfg_coef: float = 1.0,<br>attribute_dropout: Dict[str, Dict[str, float]] = {},<br>two_step_cfg: bool = False,<br>**kwargs)</span>
|
||
</code></dt>
|
||
<dd>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">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: CodebooksPatternProvider, condition_provider: ConditioningProvider,
|
||
fuser: ConditionFuser, 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.cfg_dropout = ClassifierFreeGuidanceDropout(p=cfg_dropout)
|
||
self.att_dropout = AttributeDropout(p=attribute_dropout)
|
||
self.condition_provider = condition_provider
|
||
self.fuser = fuser
|
||
self.card = card
|
||
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: torch.Tensor,
|
||
conditions: tp.List[ConditioningAttributes],
|
||
condition_tensors: tp.Optional[ConditionTensors] = None,
|
||
stage: int = -1) -> torch.Tensor:
|
||
"""Apply language model on sequence and conditions.
|
||
Given a tensor of sequence of shape [B, K, S] with K the number of codebooks and
|
||
S the sequence steps, return the logits with shape [B, card, K, S].
|
||
|
||
Args:
|
||
indices (torch.Tensor): Indices of the codes to model.
|
||
conditions (list of ConditioningAttributes): Conditions to use when modeling
|
||
the given codes. Note that when evaluating multiple time with the same conditioning
|
||
you should pre-compute those and pass them as `condition_tensors`.
|
||
condition_tensors (dict[str, ConditionType], optional): Pre-computed conditioning
|
||
tensors, see `conditions`.
|
||
stage (int): The codebook level that is being predicted. Relevant for MAGNeT
|
||
in which prediction is done in a codebook-by-codebook manner.
|
||
Takes values in range(n_q), and ignored by default.
|
||
Returns:
|
||
torch.Tensor: Logits.
|
||
"""
|
||
B, K, S = sequence.shape
|
||
assert K == self.num_codebooks, "Sequence shape must match the specified number of codebooks"
|
||
input_ = sum([self.emb[k](sequence[:, k]) for k in range(K)])
|
||
if condition_tensors is None:
|
||
assert not self._is_streaming, "Conditions tensors should be precomputed when streaming."
|
||
# apply dropout modules
|
||
conditions = self.cfg_dropout(conditions)
|
||
conditions = self.att_dropout(conditions)
|
||
tokenized = self.condition_provider.tokenize(conditions)
|
||
# encode conditions and fuse, both have a streaming cache to not recompute when generating.
|
||
condition_tensors = self.condition_provider(tokenized)
|
||
else:
|
||
assert not conditions, "Shouldn't pass both conditions and condition_tensors."
|
||
|
||
input_, cross_attention_input = self.fuser(input_, condition_tensors)
|
||
|
||
out = self.transformer(input_, cross_attention_src=cross_attention_input,
|
||
src_mask=(self.attn_mask_per_stage[stage] if stage >= 0 else None)) # type: ignore
|
||
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:]
|
||
|
||
return logits # [B, K, S, card]
|
||
|
||
def compute_predictions(
|
||
self, codes: torch.Tensor,
|
||
conditions: tp.List[ConditioningAttributes],
|
||
condition_tensors: tp.Optional[ConditionTensors] = None,
|
||
stage: int = -1,
|
||
keep_only_valid_steps: bool = True) -> LMOutput:
|
||
"""Given an input tensor of codes [B, K, T] and list of conditions, runs the model
|
||
forward using the specified codes interleaving pattern.
|
||
|
||
Args:
|
||
codes (torch.Tensor): Input codes of shape [B, K, T] with B the batch size,
|
||
K the number of codebooks and T the number of timesteps.
|
||
conditions (list of ConditioningAttributes): conditionings to use when modeling
|
||
the given codes. Note that when evaluating multiple time with the same conditioning
|
||
you should pre-compute those and pass them as `condition_tensors`.
|
||
condition_tensors (dict[str, ConditionType], optional): pre-computed conditioning
|
||
tensors, see `conditions`.
|
||
stage (int): The codebook level that is being predicted. Relevant for MAGNeT
|
||
in which prediction is done in a codebook-by-codebook manner.
|
||
Takes values in range(n_q), and ignored by default.
|
||
keep_only_valid_steps (bool): Build a sequence from the pattern up to valid (= fully defined) steps.
|
||
Steps that are beyond valid steps will be replaced by the special_token in that case.
|
||
Returns:
|
||
LMOutput: Language model outputs
|
||
logits (torch.Tensor) of shape [B, K, T, card] corresponding to the provided codes,
|
||
i.e. the first item corresponds to logits to predict the first code, meaning that
|
||
no additional shifting of codes and logits is required.
|
||
mask (torch.Tensor) of shape [B, K, T], mask over valid and invalid positions.
|
||
Given the specified interleaving strategies, parts of the logits and codes should
|
||
not be considered as valid predictions because of invalid context.
|
||
"""
|
||
B, K, T = codes.shape
|
||
codes = codes.contiguous()
|
||
# map codes [B, K, T] into pattern sequence [B, K, S] using special_token_id for masked tokens
|
||
pattern = self.pattern_provider.get_pattern(T)
|
||
sequence_codes, sequence_indexes, sequence_mask = pattern.build_pattern_sequence(
|
||
codes, self.special_token_id, keep_only_valid_steps=keep_only_valid_steps,
|
||
)
|
||
|
||
# apply model on pattern sequence
|
||
model = self if self._fsdp is None else self._fsdp
|
||
logits = model(sequence_codes, conditions, condition_tensors, stage=stage) # [B, K, S, card]
|
||
# map back the logits on pattern sequence to logits on original codes: [B, K, S, card] -> [B, K, T, card]
|
||
# and provide the corresponding mask over invalid positions of tokens
|
||
logits = logits.permute(0, 3, 1, 2) # [B, card, K, S]
|
||
# note: we use nans as special token to make it obvious if we feed unexpected logits
|
||
logits, logits_indexes, logits_mask = pattern.revert_pattern_logits(
|
||
logits, float('nan'), keep_only_valid_steps=keep_only_valid_steps
|
||
)
|
||
logits = logits.permute(0, 2, 3, 1) # [B, K, T, card]
|
||
logits_mask = logits_mask[None, :, :].expand(B, -1, -1) # [K, T] -> [B, K, T]
|
||
return LMOutput(logits, logits_mask)
|
||
|
||
def _sample_next_token(self,
|
||
sequence: torch.Tensor,
|
||
cfg_conditions: CFGConditions,
|
||
unconditional_state: State,
|
||
use_sampling: bool = False,
|
||
temp: float = 1.0,
|
||
top_k: int = 0,
|
||
top_p: float = 0.0,
|
||
cfg_coef: tp.Optional[float] = None,
|
||
cfg_coef_beta: tp.Optional[float] = None,
|
||
two_step_cfg: tp.Optional[bool] = None) -> torch.Tensor:
|
||
"""Sample next token from the model given a sequence and a set of conditions. The model supports
|
||
multiple sampling strategies (greedy sampling, softmax, top-k, top-p...).
|
||
|
||
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.
|
||
condition_tensors (dict[str, ConditionType): Set of conditions. If CFG is used,
|
||
should be twice the batch size, being the concatenation of the conditions + null conditions.
|
||
use_sampling (bool): Whether to use a sampling strategy or not.
|
||
temp (float): Sampling temperature.
|
||
top_k (int): K for "top-k" sampling.
|
||
top_p (float): P for "top-p" sampling.
|
||
cfg_coef (float, optional): classifier free guidance coefficient
|
||
cfg_coef_beta (float, optional): If None, simple classifier free guidance is used with cfg_coef.
|
||
If not None, we apply double classifier free guidance as introduced in MusicGen-Style
|
||
in paragraph 4.3 (https://arxiv.org/pdf/2407.12563). This beta coefficient is meant to
|
||
push the text condition more than the style condition in the case where both text and style
|
||
conditions are being used.
|
||
two_step_cfg (bool): Whether to run classifier free-guidance with 2 distinct steps.
|
||
|
||
Returns:
|
||
next_token (torch.Tensor): Next token tensor of shape [B, K, 1].
|
||
"""
|
||
B = sequence.shape[0]
|
||
cfg_coef = self.cfg_coef if cfg_coef is None else cfg_coef
|
||
model = self if self._fsdp is None else self._fsdp
|
||
two_step_cfg = self.two_step_cfg if two_step_cfg is None else two_step_cfg
|
||
if cfg_coef_beta is not None:
|
||
assert isinstance(cfg_conditions, dict)
|
||
condition_tensors = cfg_conditions
|
||
if condition_tensors:
|
||
# Preparing for CFG, predicting conditional text and style, conditional style
|
||
# and unconditional
|
||
sequence = torch.cat([sequence, sequence, sequence], dim=0)
|
||
all_logits = model(
|
||
sequence,
|
||
conditions=[], condition_tensors=condition_tensors)
|
||
if condition_tensors:
|
||
cond_logits, wav_logits, uncond_logits = all_logits.split(B, dim=0) # [B, K, T, card]
|
||
logits = uncond_logits + cfg_coef * (
|
||
wav_logits + cfg_coef_beta * (cond_logits - wav_logits) - uncond_logits
|
||
)
|
||
|
||
elif two_step_cfg and cfg_conditions != {}:
|
||
assert isinstance(cfg_conditions, tuple), type(cfg_conditions)
|
||
condition_tensors, null_condition_tensors = cfg_conditions
|
||
cond_logits = model(sequence, conditions=[], condition_tensors=condition_tensors)
|
||
state = self.get_streaming_state()
|
||
self.set_streaming_state(unconditional_state)
|
||
uncond_logits = model(sequence, conditions=[], condition_tensors=null_condition_tensors)
|
||
unconditional_state.update(self.get_streaming_state())
|
||
self.set_streaming_state(state)
|
||
logits = uncond_logits + (cond_logits - uncond_logits) * self.cfg_coef
|
||
else:
|
||
assert isinstance(cfg_conditions, dict)
|
||
condition_tensors = cfg_conditions
|
||
if condition_tensors:
|
||
# Preparing for CFG, predicting both conditional and unconditional logits.
|
||
sequence = torch.cat([sequence, sequence], dim=0)
|
||
all_logits = model(
|
||
sequence,
|
||
conditions=[], condition_tensors=condition_tensors)
|
||
if condition_tensors:
|
||
cond_logits, uncond_logits = all_logits.split(B, dim=0) # [B, K, T, card]
|
||
logits = uncond_logits + (cond_logits - uncond_logits) * cfg_coef
|
||
else:
|
||
logits = all_logits
|
||
|
||
logits = logits.permute(0, 1, 3, 2) # [B, K, card, T]
|
||
logits = logits[..., -1] # [B x K x card]
|
||
|
||
# Apply softmax for sampling if temp > 0. Else, do greedy sampling to avoid zero division error.
|
||
if use_sampling and temp > 0.0:
|
||
probs = torch.softmax(logits / temp, dim=-1)
|
||
if top_p > 0.0:
|
||
next_token = utils.sample_top_p(probs, p=top_p)
|
||
elif top_k > 0:
|
||
next_token = utils.sample_top_k(probs, k=top_k)
|
||
else:
|
||
next_token = utils.multinomial(probs, num_samples=1)
|
||
else:
|
||
next_token = torch.argmax(logits, dim=-1, keepdim=True)
|
||
|
||
return next_token
|
||
|
||
@torch.no_grad()
|
||
def generate(self,
|
||
prompt: tp.Optional[torch.Tensor] = None,
|
||
conditions: tp.List[ConditioningAttributes] = [],
|
||
num_samples: tp.Optional[int] = None,
|
||
max_gen_len: int = 256,
|
||
use_sampling: bool = True,
|
||
temp: float = 1.0,
|
||
top_k: int = 250,
|
||
top_p: float = 0.0,
|
||
cfg_coef: tp.Optional[float] = None,
|
||
cfg_coef_beta: tp.Optional[float] = None,
|
||
two_step_cfg: tp.Optional[bool] = None,
|
||
remove_prompts: bool = False,
|
||
check: bool = False,
|
||
callback: tp.Optional[tp.Callable[[int, int], None]] = None,
|
||
) -> torch.Tensor:
|
||
"""Generate tokens sampling from the model given a prompt or unconditionally. Generation can
|
||
be performed in a greedy fashion or using sampling with top K and top P strategies.
|
||
|
||
Args:
|
||
prompt (torch.Tensor, optional): Prompt tokens of shape [B, K, T].
|
||
conditions (list of ConditioningAttributes, optional): List of conditions.
|
||
num_samples (int, optional): Number of samples to generate when no prompt and no conditions are given.
|
||
max_gen_len (int): Maximum generation length.
|
||
use_sampling (bool): Whether to use a sampling strategy or not.
|
||
temp (float): Sampling temperature.
|
||
top_k (int): K for "top-k" sampling.
|
||
top_p (float): P for "top-p" sampling.
|
||
cfg_coef (float, optional): Classifier-free guidance coefficient.
|
||
cfg_coef_beta (float, optional): If None, simple classifier free guidance is used with cfg_coef.
|
||
If not None, we apply double classifier free guidance as introduced in MusicGen-Style
|
||
in paragraph 4.3 (https://arxiv.org/pdf/2407.12563). This beta coefficient is meant to
|
||
push the text condition more than the style condition in the case where both text and style
|
||
conditions are being used.
|
||
two_step_cfg (bool, optional): Whether to perform classifier-free guidance with two steps generation.
|
||
remove_prompts (bool): Whether to remove prompts from generation or not.
|
||
check (bool): Whether to apply further checks on generated sequence.
|
||
callback (Callback, optional): Callback function to report generation progress.
|
||
Returns:
|
||
torch.Tensor: Generated tokens.
|
||
"""
|
||
assert not self.training, "generation shouldn't be used in training mode."
|
||
first_param = next(iter(self.parameters()))
|
||
device = first_param.device
|
||
|
||
# Checking all input shapes are consistent.
|
||
possible_num_samples = []
|
||
if num_samples is not None:
|
||
possible_num_samples.append(num_samples)
|
||
elif prompt is not None:
|
||
possible_num_samples.append(prompt.shape[0])
|
||
elif conditions:
|
||
possible_num_samples.append(len(conditions))
|
||
else:
|
||
possible_num_samples.append(1)
|
||
assert [x == possible_num_samples[0] for x in possible_num_samples], "Inconsistent inputs shapes"
|
||
num_samples = possible_num_samples[0]
|
||
|
||
# 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
|
||
cfg_conditions = {}
|
||
if cfg_coef_beta is not None:
|
||
if conditions:
|
||
wav_conditions = _drop_description_condition(conditions)
|
||
null_conditions = ClassifierFreeGuidanceDropout(p=1.0)(conditions)
|
||
conditions = conditions + wav_conditions + null_conditions
|
||
tokenized = self.condition_provider.tokenize(conditions)
|
||
cfg_conditions = self.condition_provider(tokenized)
|
||
elif conditions:
|
||
two_step_cfg = self.two_step_cfg if two_step_cfg is None else two_step_cfg
|
||
if conditions:
|
||
null_conditions = ClassifierFreeGuidanceDropout(p=1.0)(conditions)
|
||
if two_step_cfg:
|
||
cfg_conditions = (
|
||
self.condition_provider(self.condition_provider.tokenize(conditions)),
|
||
self.condition_provider(self.condition_provider.tokenize(null_conditions)),
|
||
)
|
||
else:
|
||
conditions = conditions + null_conditions
|
||
tokenized = self.condition_provider.tokenize(conditions)
|
||
cfg_conditions = self.condition_provider(tokenized)
|
||
else:
|
||
cfg_conditions = {}
|
||
|
||
if prompt is None:
|
||
assert num_samples > 0
|
||
prompt = torch.zeros((num_samples, self.num_codebooks, 0), dtype=torch.long, device=device)
|
||
|
||
B, K, T = prompt.shape
|
||
start_offset = T
|
||
assert start_offset < max_gen_len
|
||
|
||
pattern = self.pattern_provider.get_pattern(max_gen_len)
|
||
# this token is used as default value for codes that are not generated yet
|
||
unknown_token = -1
|
||
|
||
# we generate codes up to the max_gen_len that will be mapped to the pattern sequence
|
||
gen_codes = torch.full((B, K, max_gen_len), unknown_token, dtype=torch.long, device=device)
|
||
# filling the gen_codes with the prompt if needed
|
||
gen_codes[..., :start_offset] = prompt
|
||
# create the gen_sequence with proper interleaving from the pattern: [B, K, S]
|
||
gen_sequence, indexes, mask = pattern.build_pattern_sequence(gen_codes, self.special_token_id)
|
||
# retrieve the start_offset in the sequence:
|
||
# it is the first sequence step that contains the `start_offset` timestep
|
||
start_offset_sequence = pattern.get_first_step_with_timesteps(start_offset)
|
||
assert start_offset_sequence is not None
|
||
|
||
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]
|
||
for offset in range(start_offset_sequence, gen_sequence_len):
|
||
# get current sequence (note that the streaming API is providing the caching over previous offsets)
|
||
curr_sequence = gen_sequence[..., prev_offset:offset]
|
||
curr_mask = mask[None, ..., prev_offset:offset].expand(B, -1, -1)
|
||
if check:
|
||
# check coherence between mask and sequence
|
||
assert (curr_sequence == torch.where(curr_mask, curr_sequence, self.special_token_id)).all()
|
||
# should never happen as gen_sequence is filled progressively
|
||
assert not (curr_sequence == unknown_token).any()
|
||
# sample next token from the model, next token shape is [B, K, 1]
|
||
next_token = self._sample_next_token(
|
||
curr_sequence, cfg_conditions, unconditional_state, use_sampling, temp, top_k, top_p,
|
||
cfg_coef=cfg_coef, cfg_coef_beta=cfg_coef_beta, two_step_cfg=two_step_cfg)
|
||
# ensure the tokens that should be masked are properly set to special_token_id
|
||
# as the model never output special_token_id
|
||
valid_mask = mask[..., offset:offset+1].expand(B, -1, -1)
|
||
next_token[~valid_mask] = self.special_token_id
|
||
# ensure we don't overwrite prompt tokens, we only write over unknown tokens
|
||
# (then mask tokens should be left as is as well, which is correct)
|
||
gen_sequence[..., offset:offset+1] = torch.where(
|
||
gen_sequence[..., offset:offset+1] == unknown_token,
|
||
next_token, gen_sequence[..., offset:offset+1]
|
||
)
|
||
prev_offset = offset
|
||
if callback is not None:
|
||
callback(1 + offset - start_offset_sequence, gen_sequence_len - start_offset_sequence)
|
||
unconditional_state.clear()
|
||
|
||
# ensure sequence has been entirely filled
|
||
assert not (gen_sequence == unknown_token).any()
|
||
# ensure gen_sequence pattern and mask are matching
|
||
# which means the gen_sequence is valid according to the pattern
|
||
assert (
|
||
gen_sequence == torch.where(mask[None, ...].expand(B, -1, -1), gen_sequence, self.special_token_id)
|
||
).all()
|
||
# get back the codes, trimming the prompt if needed and cutting potentially incomplete timesteps
|
||
out_codes, out_indexes, out_mask = pattern.revert_pattern_sequence(gen_sequence, special_token=unknown_token)
|
||
|
||
# sanity checks over the returned codes and corresponding masks
|
||
assert (out_codes[..., :max_gen_len] != unknown_token).all()
|
||
assert (out_mask[..., :max_gen_len] == 1).all()
|
||
|
||
out_start_offset = start_offset if remove_prompts else 0
|
||
out_codes = out_codes[..., out_start_offset:max_gen_len]
|
||
|
||
# ensure the returned codes are all valid
|
||
assert (out_codes >= 0).all() and (out_codes <= self.card).all()
|
||
return out_codes</code></pre>
|
||
</details>
|
||
<div class="desc"><p>Transformer-based language model on multiple streams of codes.</p>
|
||
<h2 id="args">Args</h2>
|
||
<dl>
|
||
<dt><strong><code>pattern_provider</code></strong> : <code>CodebooksPatternProvider</code></dt>
|
||
<dd>Pattern provider for codebook interleaving.</dd>
|
||
<dt><strong><code>condition_provider</code></strong> : <code>MusicConditioningProvider</code></dt>
|
||
<dd>Conditioning provider from metadata.</dd>
|
||
<dt><strong><code>fuser</code></strong> : <code>ConditionFuser</code></dt>
|
||
<dd>Fuser handling the fusing of conditions with language model input.</dd>
|
||
<dt><strong><code>n_q</code></strong> : <code>int</code></dt>
|
||
<dd>Number of parallel streams to model.</dd>
|
||
<dt><strong><code>card</code></strong> : <code>int</code></dt>
|
||
<dd>Cardinality, vocabulary size.</dd>
|
||
<dt><strong><code>dim</code></strong> : <code>int</code></dt>
|
||
<dd>Dimension of the transformer encoder.</dd>
|
||
<dt><strong><code>num_heads</code></strong> : <code>int</code></dt>
|
||
<dd>Number of heads for the transformer encoder.</dd>
|
||
<dt><strong><code>hidden_scale</code></strong> : <code>int</code></dt>
|
||
<dd>Scale for hidden feed forward dimension of the transformer encoder.</dd>
|
||
<dt><strong><code>norm</code></strong> : <code>str</code></dt>
|
||
<dd>Normalization method.</dd>
|
||
<dt><strong><code>norm_first</code></strong> : <code>bool</code></dt>
|
||
<dd>Use pre-norm instead of post-norm.</dd>
|
||
<dt><strong><code>emb_lr</code></strong> : <code>float</code>, optional</dt>
|
||
<dd>Embedding-specific learning rate.</dd>
|
||
<dt><strong><code>bias_proj</code></strong> : <code>bool</code></dt>
|
||
<dd>Use bias for output projections.</dd>
|
||
<dt><strong><code>weight_init</code></strong> : <code>str</code>, optional</dt>
|
||
<dd>Method for weight initialization.</dd>
|
||
<dt><strong><code>depthwise_init</code></strong> : <code>str</code>, optional</dt>
|
||
<dd>Method for depthwise weight initialization.</dd>
|
||
<dt><strong><code>zero_bias_init</code></strong> : <code>bool</code></dt>
|
||
<dd>If true and bias in Linears, initialize bias to zeros.</dd>
|
||
<dt><strong><code>cfg_dropout</code></strong> : <code>float</code></dt>
|
||
<dd>Classifier-free guidance dropout.</dd>
|
||
<dt><strong><code>cfg_coef</code></strong> : <code>float</code></dt>
|
||
<dd>Classifier-free guidance coefficient.</dd>
|
||
<dt><strong><code>attribute_dropout</code></strong> : <code>dict</code></dt>
|
||
<dd>Attribute dropout probabilities.</dd>
|
||
<dt><strong><code>two_step_cfg</code></strong> : <code>bool</code></dt>
|
||
<dd>Whether to run classifier free-guidance with 2 distinct steps.</dd>
|
||
<dt><strong><code>**kwargs</code></strong></dt>
|
||
<dd>Additional parameters for the transformer encoder.</dd>
|
||
</dl>
|
||
<p>Initializes internal Module state, shared by both nn.Module and ScriptModule.</p></div>
|
||
<h3>Ancestors</h3>
|
||
<ul class="hlist">
|
||
<li><a title="audiocraft.modules.streaming.StreamingModule" href="../modules/streaming.html#audiocraft.modules.streaming.StreamingModule">StreamingModule</a></li>
|
||
<li>torch.nn.modules.module.Module</li>
|
||
</ul>
|
||
<h3>Subclasses</h3>
|
||
<ul class="hlist">
|
||
<li><a title="audiocraft.models.lm_magnet.MagnetLMModel" href="lm_magnet.html#audiocraft.models.lm_magnet.MagnetLMModel">MagnetLMModel</a></li>
|
||
</ul>
|
||
<h3>Class variables</h3>
|
||
<dl>
|
||
<dt id="audiocraft.models.lm.LMModel.call_super_init"><code class="name">var <span class="ident">call_super_init</span> : bool</code></dt>
|
||
<dd>
|
||
<div class="desc"></div>
|
||
</dd>
|
||
<dt id="audiocraft.models.lm.LMModel.dump_patches"><code class="name">var <span class="ident">dump_patches</span> : bool</code></dt>
|
||
<dd>
|
||
<div class="desc"></div>
|
||
</dd>
|
||
<dt id="audiocraft.models.lm.LMModel.training"><code class="name">var <span class="ident">training</span> : bool</code></dt>
|
||
<dd>
|
||
<div class="desc"></div>
|
||
</dd>
|
||
</dl>
|
||
<h3>Instance variables</h3>
|
||
<dl>
|
||
<dt id="audiocraft.models.lm.LMModel.num_codebooks"><code class="name">prop <span class="ident">num_codebooks</span> : int</code></dt>
|
||
<dd>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">@property
|
||
def num_codebooks(self) -> int:
|
||
return self.n_q</code></pre>
|
||
</details>
|
||
<div class="desc"></div>
|
||
</dd>
|
||
<dt id="audiocraft.models.lm.LMModel.special_token_id"><code class="name">prop <span class="ident">special_token_id</span> : int</code></dt>
|
||
<dd>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">@property
|
||
def special_token_id(self) -> int:
|
||
return self.card</code></pre>
|
||
</details>
|
||
<div class="desc"></div>
|
||
</dd>
|
||
</dl>
|
||
<h3>Methods</h3>
|
||
<dl>
|
||
<dt id="audiocraft.models.lm.LMModel.compute_predictions"><code class="name flex">
|
||
<span>def <span class="ident">compute_predictions</span></span>(<span>self,<br>codes: torch.Tensor,<br>conditions: List[<a title="audiocraft.modules.conditioners.ConditioningAttributes" href="../modules/conditioners.html#audiocraft.modules.conditioners.ConditioningAttributes">ConditioningAttributes</a>],<br>condition_tensors: Dict[str, Tuple[torch.Tensor, torch.Tensor]] | None = None,<br>stage: int = -1,<br>keep_only_valid_steps: bool = True) ‑> <a title="audiocraft.models.lm.LMOutput" href="#audiocraft.models.lm.LMOutput">LMOutput</a></span>
|
||
</code></dt>
|
||
<dd>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">def compute_predictions(
|
||
self, codes: torch.Tensor,
|
||
conditions: tp.List[ConditioningAttributes],
|
||
condition_tensors: tp.Optional[ConditionTensors] = None,
|
||
stage: int = -1,
|
||
keep_only_valid_steps: bool = True) -> LMOutput:
|
||
"""Given an input tensor of codes [B, K, T] and list of conditions, runs the model
|
||
forward using the specified codes interleaving pattern.
|
||
|
||
Args:
|
||
codes (torch.Tensor): Input codes of shape [B, K, T] with B the batch size,
|
||
K the number of codebooks and T the number of timesteps.
|
||
conditions (list of ConditioningAttributes): conditionings to use when modeling
|
||
the given codes. Note that when evaluating multiple time with the same conditioning
|
||
you should pre-compute those and pass them as `condition_tensors`.
|
||
condition_tensors (dict[str, ConditionType], optional): pre-computed conditioning
|
||
tensors, see `conditions`.
|
||
stage (int): The codebook level that is being predicted. Relevant for MAGNeT
|
||
in which prediction is done in a codebook-by-codebook manner.
|
||
Takes values in range(n_q), and ignored by default.
|
||
keep_only_valid_steps (bool): Build a sequence from the pattern up to valid (= fully defined) steps.
|
||
Steps that are beyond valid steps will be replaced by the special_token in that case.
|
||
Returns:
|
||
LMOutput: Language model outputs
|
||
logits (torch.Tensor) of shape [B, K, T, card] corresponding to the provided codes,
|
||
i.e. the first item corresponds to logits to predict the first code, meaning that
|
||
no additional shifting of codes and logits is required.
|
||
mask (torch.Tensor) of shape [B, K, T], mask over valid and invalid positions.
|
||
Given the specified interleaving strategies, parts of the logits and codes should
|
||
not be considered as valid predictions because of invalid context.
|
||
"""
|
||
B, K, T = codes.shape
|
||
codes = codes.contiguous()
|
||
# map codes [B, K, T] into pattern sequence [B, K, S] using special_token_id for masked tokens
|
||
pattern = self.pattern_provider.get_pattern(T)
|
||
sequence_codes, sequence_indexes, sequence_mask = pattern.build_pattern_sequence(
|
||
codes, self.special_token_id, keep_only_valid_steps=keep_only_valid_steps,
|
||
)
|
||
|
||
# apply model on pattern sequence
|
||
model = self if self._fsdp is None else self._fsdp
|
||
logits = model(sequence_codes, conditions, condition_tensors, stage=stage) # [B, K, S, card]
|
||
# map back the logits on pattern sequence to logits on original codes: [B, K, S, card] -> [B, K, T, card]
|
||
# and provide the corresponding mask over invalid positions of tokens
|
||
logits = logits.permute(0, 3, 1, 2) # [B, card, K, S]
|
||
# note: we use nans as special token to make it obvious if we feed unexpected logits
|
||
logits, logits_indexes, logits_mask = pattern.revert_pattern_logits(
|
||
logits, float('nan'), keep_only_valid_steps=keep_only_valid_steps
|
||
)
|
||
logits = logits.permute(0, 2, 3, 1) # [B, K, T, card]
|
||
logits_mask = logits_mask[None, :, :].expand(B, -1, -1) # [K, T] -> [B, K, T]
|
||
return LMOutput(logits, logits_mask)</code></pre>
|
||
</details>
|
||
<div class="desc"><p>Given an input tensor of codes [B, K, T] and list of conditions, runs the model
|
||
forward using the specified codes interleaving pattern.</p>
|
||
<h2 id="args">Args</h2>
|
||
<dl>
|
||
<dt><strong><code>codes</code></strong> : <code>torch.Tensor</code></dt>
|
||
<dd>Input codes of shape [B, K, T] with B the batch size,
|
||
K the number of codebooks and T the number of timesteps.</dd>
|
||
<dt><strong><code>conditions</code></strong> : <code>list</code> of <code>ConditioningAttributes</code></dt>
|
||
<dd>conditionings to use when modeling
|
||
the given codes. Note that when evaluating multiple time with the same conditioning
|
||
you should pre-compute those and pass them as <code>condition_tensors</code>.</dd>
|
||
<dt><strong><code>condition_tensors</code></strong> : <code>dict[str, ConditionType]</code>, optional</dt>
|
||
<dd>pre-computed conditioning
|
||
tensors, see <code>conditions</code>.</dd>
|
||
<dt><strong><code>stage</code></strong> : <code>int</code></dt>
|
||
<dd>The codebook level that is being predicted. Relevant for MAGNeT
|
||
in which prediction is done in a codebook-by-codebook manner.
|
||
Takes values in range(n_q), and ignored by default.</dd>
|
||
<dt><strong><code>keep_only_valid_steps</code></strong> : <code>bool</code></dt>
|
||
<dd>Build a sequence from the pattern up to valid (= fully defined) steps.
|
||
Steps that are beyond valid steps will be replaced by the special_token in that case.</dd>
|
||
</dl>
|
||
<h2 id="returns">Returns</h2>
|
||
<dl>
|
||
<dt><code><a title="audiocraft.models.lm.LMOutput" href="#audiocraft.models.lm.LMOutput">LMOutput</a></code></dt>
|
||
<dd>Language model outputs
|
||
logits (torch.Tensor) of shape [B, K, T, card] corresponding to the provided codes,
|
||
i.e. the first item corresponds to logits to predict the first code, meaning that
|
||
no additional shifting of codes and logits is required.
|
||
mask (torch.Tensor) of shape [B, K, T], mask over valid and invalid positions.
|
||
Given the specified interleaving strategies, parts of the logits and codes should
|
||
not be considered as valid predictions because of invalid context.</dd>
|
||
</dl></div>
|
||
</dd>
|
||
<dt id="audiocraft.models.lm.LMModel.forward"><code class="name flex">
|
||
<span>def <span class="ident">forward</span></span>(<span>self,<br>sequence: torch.Tensor,<br>conditions: List[<a title="audiocraft.modules.conditioners.ConditioningAttributes" href="../modules/conditioners.html#audiocraft.modules.conditioners.ConditioningAttributes">ConditioningAttributes</a>],<br>condition_tensors: Dict[str, Tuple[torch.Tensor, torch.Tensor]] | None = None,<br>stage: int = -1) ‑> torch.Tensor</span>
|
||
</code></dt>
|
||
<dd>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">def forward(self, sequence: torch.Tensor,
|
||
conditions: tp.List[ConditioningAttributes],
|
||
condition_tensors: tp.Optional[ConditionTensors] = None,
|
||
stage: int = -1) -> torch.Tensor:
|
||
"""Apply language model on sequence and conditions.
|
||
Given a tensor of sequence of shape [B, K, S] with K the number of codebooks and
|
||
S the sequence steps, return the logits with shape [B, card, K, S].
|
||
|
||
Args:
|
||
indices (torch.Tensor): Indices of the codes to model.
|
||
conditions (list of ConditioningAttributes): Conditions to use when modeling
|
||
the given codes. Note that when evaluating multiple time with the same conditioning
|
||
you should pre-compute those and pass them as `condition_tensors`.
|
||
condition_tensors (dict[str, ConditionType], optional): Pre-computed conditioning
|
||
tensors, see `conditions`.
|
||
stage (int): The codebook level that is being predicted. Relevant for MAGNeT
|
||
in which prediction is done in a codebook-by-codebook manner.
|
||
Takes values in range(n_q), and ignored by default.
|
||
Returns:
|
||
torch.Tensor: Logits.
|
||
"""
|
||
B, K, S = sequence.shape
|
||
assert K == self.num_codebooks, "Sequence shape must match the specified number of codebooks"
|
||
input_ = sum([self.emb[k](sequence[:, k]) for k in range(K)])
|
||
if condition_tensors is None:
|
||
assert not self._is_streaming, "Conditions tensors should be precomputed when streaming."
|
||
# apply dropout modules
|
||
conditions = self.cfg_dropout(conditions)
|
||
conditions = self.att_dropout(conditions)
|
||
tokenized = self.condition_provider.tokenize(conditions)
|
||
# encode conditions and fuse, both have a streaming cache to not recompute when generating.
|
||
condition_tensors = self.condition_provider(tokenized)
|
||
else:
|
||
assert not conditions, "Shouldn't pass both conditions and condition_tensors."
|
||
|
||
input_, cross_attention_input = self.fuser(input_, condition_tensors)
|
||
|
||
out = self.transformer(input_, cross_attention_src=cross_attention_input,
|
||
src_mask=(self.attn_mask_per_stage[stage] if stage >= 0 else None)) # type: ignore
|
||
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:]
|
||
|
||
return logits # [B, K, S, card]</code></pre>
|
||
</details>
|
||
<div class="desc"><p>Apply language model on sequence and conditions.
|
||
Given a tensor of sequence of shape [B, K, S] with K the number of codebooks and
|
||
S the sequence steps, return the logits with shape [B, card, K, S].</p>
|
||
<h2 id="args">Args</h2>
|
||
<dl>
|
||
<dt><strong><code>indices</code></strong> : <code>torch.Tensor</code></dt>
|
||
<dd>Indices of the codes to model.</dd>
|
||
<dt><strong><code>conditions</code></strong> : <code>list</code> of <code>ConditioningAttributes</code></dt>
|
||
<dd>Conditions to use when modeling
|
||
the given codes. Note that when evaluating multiple time with the same conditioning
|
||
you should pre-compute those and pass them as <code>condition_tensors</code>.</dd>
|
||
<dt><strong><code>condition_tensors</code></strong> : <code>dict[str, ConditionType]</code>, optional</dt>
|
||
<dd>Pre-computed conditioning
|
||
tensors, see <code>conditions</code>.</dd>
|
||
<dt><strong><code>stage</code></strong> : <code>int</code></dt>
|
||
<dd>The codebook level that is being predicted. Relevant for MAGNeT
|
||
in which prediction is done in a codebook-by-codebook manner.
|
||
Takes values in range(n_q), and ignored by default.</dd>
|
||
</dl>
|
||
<h2 id="returns">Returns</h2>
|
||
<dl>
|
||
<dt><code>torch.Tensor</code></dt>
|
||
<dd>Logits.</dd>
|
||
</dl></div>
|
||
</dd>
|
||
<dt id="audiocraft.models.lm.LMModel.generate"><code class="name flex">
|
||
<span>def <span class="ident">generate</span></span>(<span>self,<br>prompt: torch.Tensor | None = None,<br>conditions: List[<a title="audiocraft.modules.conditioners.ConditioningAttributes" href="../modules/conditioners.html#audiocraft.modules.conditioners.ConditioningAttributes">ConditioningAttributes</a>] = [],<br>num_samples: int | None = None,<br>max_gen_len: int = 256,<br>use_sampling: bool = True,<br>temp: float = 1.0,<br>top_k: int = 250,<br>top_p: float = 0.0,<br>cfg_coef: float | None = None,<br>cfg_coef_beta: float | None = None,<br>two_step_cfg: bool | None = None,<br>remove_prompts: bool = False,<br>check: bool = False,<br>callback: Callable[[int, int], None] | None = None) ‑> torch.Tensor</span>
|
||
</code></dt>
|
||
<dd>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">@torch.no_grad()
|
||
def generate(self,
|
||
prompt: tp.Optional[torch.Tensor] = None,
|
||
conditions: tp.List[ConditioningAttributes] = [],
|
||
num_samples: tp.Optional[int] = None,
|
||
max_gen_len: int = 256,
|
||
use_sampling: bool = True,
|
||
temp: float = 1.0,
|
||
top_k: int = 250,
|
||
top_p: float = 0.0,
|
||
cfg_coef: tp.Optional[float] = None,
|
||
cfg_coef_beta: tp.Optional[float] = None,
|
||
two_step_cfg: tp.Optional[bool] = None,
|
||
remove_prompts: bool = False,
|
||
check: bool = False,
|
||
callback: tp.Optional[tp.Callable[[int, int], None]] = None,
|
||
) -> torch.Tensor:
|
||
"""Generate tokens sampling from the model given a prompt or unconditionally. Generation can
|
||
be performed in a greedy fashion or using sampling with top K and top P strategies.
|
||
|
||
Args:
|
||
prompt (torch.Tensor, optional): Prompt tokens of shape [B, K, T].
|
||
conditions (list of ConditioningAttributes, optional): List of conditions.
|
||
num_samples (int, optional): Number of samples to generate when no prompt and no conditions are given.
|
||
max_gen_len (int): Maximum generation length.
|
||
use_sampling (bool): Whether to use a sampling strategy or not.
|
||
temp (float): Sampling temperature.
|
||
top_k (int): K for "top-k" sampling.
|
||
top_p (float): P for "top-p" sampling.
|
||
cfg_coef (float, optional): Classifier-free guidance coefficient.
|
||
cfg_coef_beta (float, optional): If None, simple classifier free guidance is used with cfg_coef.
|
||
If not None, we apply double classifier free guidance as introduced in MusicGen-Style
|
||
in paragraph 4.3 (https://arxiv.org/pdf/2407.12563). This beta coefficient is meant to
|
||
push the text condition more than the style condition in the case where both text and style
|
||
conditions are being used.
|
||
two_step_cfg (bool, optional): Whether to perform classifier-free guidance with two steps generation.
|
||
remove_prompts (bool): Whether to remove prompts from generation or not.
|
||
check (bool): Whether to apply further checks on generated sequence.
|
||
callback (Callback, optional): Callback function to report generation progress.
|
||
Returns:
|
||
torch.Tensor: Generated tokens.
|
||
"""
|
||
assert not self.training, "generation shouldn't be used in training mode."
|
||
first_param = next(iter(self.parameters()))
|
||
device = first_param.device
|
||
|
||
# Checking all input shapes are consistent.
|
||
possible_num_samples = []
|
||
if num_samples is not None:
|
||
possible_num_samples.append(num_samples)
|
||
elif prompt is not None:
|
||
possible_num_samples.append(prompt.shape[0])
|
||
elif conditions:
|
||
possible_num_samples.append(len(conditions))
|
||
else:
|
||
possible_num_samples.append(1)
|
||
assert [x == possible_num_samples[0] for x in possible_num_samples], "Inconsistent inputs shapes"
|
||
num_samples = possible_num_samples[0]
|
||
|
||
# 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
|
||
cfg_conditions = {}
|
||
if cfg_coef_beta is not None:
|
||
if conditions:
|
||
wav_conditions = _drop_description_condition(conditions)
|
||
null_conditions = ClassifierFreeGuidanceDropout(p=1.0)(conditions)
|
||
conditions = conditions + wav_conditions + null_conditions
|
||
tokenized = self.condition_provider.tokenize(conditions)
|
||
cfg_conditions = self.condition_provider(tokenized)
|
||
elif conditions:
|
||
two_step_cfg = self.two_step_cfg if two_step_cfg is None else two_step_cfg
|
||
if conditions:
|
||
null_conditions = ClassifierFreeGuidanceDropout(p=1.0)(conditions)
|
||
if two_step_cfg:
|
||
cfg_conditions = (
|
||
self.condition_provider(self.condition_provider.tokenize(conditions)),
|
||
self.condition_provider(self.condition_provider.tokenize(null_conditions)),
|
||
)
|
||
else:
|
||
conditions = conditions + null_conditions
|
||
tokenized = self.condition_provider.tokenize(conditions)
|
||
cfg_conditions = self.condition_provider(tokenized)
|
||
else:
|
||
cfg_conditions = {}
|
||
|
||
if prompt is None:
|
||
assert num_samples > 0
|
||
prompt = torch.zeros((num_samples, self.num_codebooks, 0), dtype=torch.long, device=device)
|
||
|
||
B, K, T = prompt.shape
|
||
start_offset = T
|
||
assert start_offset < max_gen_len
|
||
|
||
pattern = self.pattern_provider.get_pattern(max_gen_len)
|
||
# this token is used as default value for codes that are not generated yet
|
||
unknown_token = -1
|
||
|
||
# we generate codes up to the max_gen_len that will be mapped to the pattern sequence
|
||
gen_codes = torch.full((B, K, max_gen_len), unknown_token, dtype=torch.long, device=device)
|
||
# filling the gen_codes with the prompt if needed
|
||
gen_codes[..., :start_offset] = prompt
|
||
# create the gen_sequence with proper interleaving from the pattern: [B, K, S]
|
||
gen_sequence, indexes, mask = pattern.build_pattern_sequence(gen_codes, self.special_token_id)
|
||
# retrieve the start_offset in the sequence:
|
||
# it is the first sequence step that contains the `start_offset` timestep
|
||
start_offset_sequence = pattern.get_first_step_with_timesteps(start_offset)
|
||
assert start_offset_sequence is not None
|
||
|
||
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]
|
||
for offset in range(start_offset_sequence, gen_sequence_len):
|
||
# get current sequence (note that the streaming API is providing the caching over previous offsets)
|
||
curr_sequence = gen_sequence[..., prev_offset:offset]
|
||
curr_mask = mask[None, ..., prev_offset:offset].expand(B, -1, -1)
|
||
if check:
|
||
# check coherence between mask and sequence
|
||
assert (curr_sequence == torch.where(curr_mask, curr_sequence, self.special_token_id)).all()
|
||
# should never happen as gen_sequence is filled progressively
|
||
assert not (curr_sequence == unknown_token).any()
|
||
# sample next token from the model, next token shape is [B, K, 1]
|
||
next_token = self._sample_next_token(
|
||
curr_sequence, cfg_conditions, unconditional_state, use_sampling, temp, top_k, top_p,
|
||
cfg_coef=cfg_coef, cfg_coef_beta=cfg_coef_beta, two_step_cfg=two_step_cfg)
|
||
# ensure the tokens that should be masked are properly set to special_token_id
|
||
# as the model never output special_token_id
|
||
valid_mask = mask[..., offset:offset+1].expand(B, -1, -1)
|
||
next_token[~valid_mask] = self.special_token_id
|
||
# ensure we don't overwrite prompt tokens, we only write over unknown tokens
|
||
# (then mask tokens should be left as is as well, which is correct)
|
||
gen_sequence[..., offset:offset+1] = torch.where(
|
||
gen_sequence[..., offset:offset+1] == unknown_token,
|
||
next_token, gen_sequence[..., offset:offset+1]
|
||
)
|
||
prev_offset = offset
|
||
if callback is not None:
|
||
callback(1 + offset - start_offset_sequence, gen_sequence_len - start_offset_sequence)
|
||
unconditional_state.clear()
|
||
|
||
# ensure sequence has been entirely filled
|
||
assert not (gen_sequence == unknown_token).any()
|
||
# ensure gen_sequence pattern and mask are matching
|
||
# which means the gen_sequence is valid according to the pattern
|
||
assert (
|
||
gen_sequence == torch.where(mask[None, ...].expand(B, -1, -1), gen_sequence, self.special_token_id)
|
||
).all()
|
||
# get back the codes, trimming the prompt if needed and cutting potentially incomplete timesteps
|
||
out_codes, out_indexes, out_mask = pattern.revert_pattern_sequence(gen_sequence, special_token=unknown_token)
|
||
|
||
# sanity checks over the returned codes and corresponding masks
|
||
assert (out_codes[..., :max_gen_len] != unknown_token).all()
|
||
assert (out_mask[..., :max_gen_len] == 1).all()
|
||
|
||
out_start_offset = start_offset if remove_prompts else 0
|
||
out_codes = out_codes[..., out_start_offset:max_gen_len]
|
||
|
||
# ensure the returned codes are all valid
|
||
assert (out_codes >= 0).all() and (out_codes <= self.card).all()
|
||
return out_codes</code></pre>
|
||
</details>
|
||
<div class="desc"><p>Generate tokens sampling from the model given a prompt or unconditionally. Generation can
|
||
be performed in a greedy fashion or using sampling with top K and top P strategies.</p>
|
||
<h2 id="args">Args</h2>
|
||
<dl>
|
||
<dt><strong><code>prompt</code></strong> : <code>torch.Tensor</code>, optional</dt>
|
||
<dd>Prompt tokens of shape [B, K, T].</dd>
|
||
<dt><strong><code>conditions</code></strong> : <code>list</code> of <code>ConditioningAttributes</code>, optional</dt>
|
||
<dd>List of conditions.</dd>
|
||
<dt><strong><code>num_samples</code></strong> : <code>int</code>, optional</dt>
|
||
<dd>Number of samples to generate when no prompt and no conditions are given.</dd>
|
||
<dt><strong><code>max_gen_len</code></strong> : <code>int</code></dt>
|
||
<dd>Maximum generation length.</dd>
|
||
<dt><strong><code>use_sampling</code></strong> : <code>bool</code></dt>
|
||
<dd>Whether to use a sampling strategy or not.</dd>
|
||
<dt><strong><code>temp</code></strong> : <code>float</code></dt>
|
||
<dd>Sampling temperature.</dd>
|
||
<dt><strong><code>top_k</code></strong> : <code>int</code></dt>
|
||
<dd>K for "top-k" sampling.</dd>
|
||
<dt><strong><code>top_p</code></strong> : <code>float</code></dt>
|
||
<dd>P for "top-p" sampling.</dd>
|
||
<dt><strong><code>cfg_coef</code></strong> : <code>float</code>, optional</dt>
|
||
<dd>Classifier-free guidance coefficient.</dd>
|
||
<dt><strong><code>cfg_coef_beta</code></strong> : <code>float</code>, optional</dt>
|
||
<dd>If None, simple classifier free guidance is used with cfg_coef.
|
||
If not None, we apply double classifier free guidance as introduced in MusicGen-Style
|
||
in paragraph 4.3 (<a href="https://arxiv.org/pdf/2407.12563">https://arxiv.org/pdf/2407.12563</a>). This beta coefficient is meant to
|
||
push the text condition more than the style condition in the case where both text and style
|
||
conditions are being used.</dd>
|
||
<dt><strong><code>two_step_cfg</code></strong> : <code>bool</code>, optional</dt>
|
||
<dd>Whether to perform classifier-free guidance with two steps generation.</dd>
|
||
<dt><strong><code>remove_prompts</code></strong> : <code>bool</code></dt>
|
||
<dd>Whether to remove prompts from generation or not.</dd>
|
||
<dt><strong><code>check</code></strong> : <code>bool</code></dt>
|
||
<dd>Whether to apply further checks on generated sequence.</dd>
|
||
<dt><strong><code>callback</code></strong> : <code>Callback</code>, optional</dt>
|
||
<dd>Callback function to report generation progress.</dd>
|
||
</dl>
|
||
<h2 id="returns">Returns</h2>
|
||
<dl>
|
||
<dt><code>torch.Tensor</code></dt>
|
||
<dd>Generated tokens.</dd>
|
||
</dl></div>
|
||
</dd>
|
||
</dl>
|
||
<h3>Inherited members</h3>
|
||
<ul class="hlist">
|
||
<li><code><b><a title="audiocraft.modules.streaming.StreamingModule" href="../modules/streaming.html#audiocraft.modules.streaming.StreamingModule">StreamingModule</a></b></code>:
|
||
<ul class="hlist">
|
||
<li><code><a title="audiocraft.modules.streaming.StreamingModule.flush" href="../modules/streaming.html#audiocraft.modules.streaming.StreamingModule.flush">flush</a></code></li>
|
||
<li><code><a title="audiocraft.modules.streaming.StreamingModule.get_streaming_state" href="../modules/streaming.html#audiocraft.modules.streaming.StreamingModule.get_streaming_state">get_streaming_state</a></code></li>
|
||
<li><code><a title="audiocraft.modules.streaming.StreamingModule.reset_streaming" href="../modules/streaming.html#audiocraft.modules.streaming.StreamingModule.reset_streaming">reset_streaming</a></code></li>
|
||
<li><code><a title="audiocraft.modules.streaming.StreamingModule.set_streaming_state" href="../modules/streaming.html#audiocraft.modules.streaming.StreamingModule.set_streaming_state">set_streaming_state</a></code></li>
|
||
<li><code><a title="audiocraft.modules.streaming.StreamingModule.streaming" href="../modules/streaming.html#audiocraft.modules.streaming.StreamingModule.streaming">streaming</a></code></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</dd>
|
||
<dt id="audiocraft.models.lm.LMOutput"><code class="flex name class">
|
||
<span>class <span class="ident">LMOutput</span></span>
|
||
<span>(</span><span>logits: torch.Tensor, mask: torch.Tensor)</span>
|
||
</code></dt>
|
||
<dd>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">@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]</code></pre>
|
||
</details>
|
||
<div class="desc"><p>LMOutput(logits: torch.Tensor, mask: torch.Tensor)</p></div>
|
||
<h3>Class variables</h3>
|
||
<dl>
|
||
<dt id="audiocraft.models.lm.LMOutput.logits"><code class="name">var <span class="ident">logits</span> : torch.Tensor</code></dt>
|
||
<dd>
|
||
<div class="desc"></div>
|
||
</dd>
|
||
<dt id="audiocraft.models.lm.LMOutput.mask"><code class="name">var <span class="ident">mask</span> : torch.Tensor</code></dt>
|
||
<dd>
|
||
<div class="desc"></div>
|
||
</dd>
|
||
</dl>
|
||
</dd>
|
||
<dt id="audiocraft.models.lm.ScaledEmbedding"><code class="flex name class">
|
||
<span>class <span class="ident">ScaledEmbedding</span></span>
|
||
<span>(</span><span>*args, lr=None, **kwargs)</span>
|
||
</code></dt>
|
||
<dd>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">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</code></pre>
|
||
</details>
|
||
<div class="desc"><p>Boost learning rate for embeddings (with <code>scale</code>).</p>
|
||
<p>Initializes internal Module state, shared by both nn.Module and ScriptModule.</p></div>
|
||
<h3>Ancestors</h3>
|
||
<ul class="hlist">
|
||
<li>torch.nn.modules.sparse.Embedding</li>
|
||
<li>torch.nn.modules.module.Module</li>
|
||
</ul>
|
||
<h3>Class variables</h3>
|
||
<dl>
|
||
<dt id="audiocraft.models.lm.ScaledEmbedding.embedding_dim"><code class="name">var <span class="ident">embedding_dim</span> : int</code></dt>
|
||
<dd>
|
||
<div class="desc"></div>
|
||
</dd>
|
||
<dt id="audiocraft.models.lm.ScaledEmbedding.freeze"><code class="name">var <span class="ident">freeze</span> : bool</code></dt>
|
||
<dd>
|
||
<div class="desc"></div>
|
||
</dd>
|
||
<dt id="audiocraft.models.lm.ScaledEmbedding.max_norm"><code class="name">var <span class="ident">max_norm</span> : float | None</code></dt>
|
||
<dd>
|
||
<div class="desc"></div>
|
||
</dd>
|
||
<dt id="audiocraft.models.lm.ScaledEmbedding.norm_type"><code class="name">var <span class="ident">norm_type</span> : float</code></dt>
|
||
<dd>
|
||
<div class="desc"></div>
|
||
</dd>
|
||
<dt id="audiocraft.models.lm.ScaledEmbedding.num_embeddings"><code class="name">var <span class="ident">num_embeddings</span> : int</code></dt>
|
||
<dd>
|
||
<div class="desc"></div>
|
||
</dd>
|
||
<dt id="audiocraft.models.lm.ScaledEmbedding.padding_idx"><code class="name">var <span class="ident">padding_idx</span> : int | None</code></dt>
|
||
<dd>
|
||
<div class="desc"></div>
|
||
</dd>
|
||
<dt id="audiocraft.models.lm.ScaledEmbedding.scale_grad_by_freq"><code class="name">var <span class="ident">scale_grad_by_freq</span> : bool</code></dt>
|
||
<dd>
|
||
<div class="desc"></div>
|
||
</dd>
|
||
<dt id="audiocraft.models.lm.ScaledEmbedding.sparse"><code class="name">var <span class="ident">sparse</span> : bool</code></dt>
|
||
<dd>
|
||
<div class="desc"></div>
|
||
</dd>
|
||
<dt id="audiocraft.models.lm.ScaledEmbedding.weight"><code class="name">var <span class="ident">weight</span> : torch.Tensor</code></dt>
|
||
<dd>
|
||
<div class="desc"></div>
|
||
</dd>
|
||
</dl>
|
||
<h3>Methods</h3>
|
||
<dl>
|
||
<dt id="audiocraft.models.lm.ScaledEmbedding.make_optim_group"><code class="name flex">
|
||
<span>def <span class="ident">make_optim_group</span></span>(<span>self)</span>
|
||
</code></dt>
|
||
<dd>
|
||
<details class="source">
|
||
<summary>
|
||
<span>Expand source code</span>
|
||
</summary>
|
||
<pre><code class="python">def make_optim_group(self):
|
||
group = {"params": list(self.parameters())}
|
||
if self.lr is not None:
|
||
group["lr"] = self.lr
|
||
return group</code></pre>
|
||
</details>
|
||
<div class="desc"></div>
|
||
</dd>
|
||
</dl>
|
||
</dd>
|
||
</dl>
|
||
</section>
|
||
</article>
|
||
<nav id="sidebar">
|
||
<div class="toc">
|
||
<ul></ul>
|
||
</div>
|
||
<ul id="index">
|
||
<li><h3>Super-module</h3>
|
||
<ul>
|
||
<li><code><a title="audiocraft.models" href="index.html">audiocraft.models</a></code></li>
|
||
</ul>
|
||
</li>
|
||
<li><h3><a href="#header-functions">Functions</a></h3>
|
||
<ul class="">
|
||
<li><code><a title="audiocraft.models.lm.get_init_fn" href="#audiocraft.models.lm.get_init_fn">get_init_fn</a></code></li>
|
||
<li><code><a title="audiocraft.models.lm.init_layer" href="#audiocraft.models.lm.init_layer">init_layer</a></code></li>
|
||
</ul>
|
||
</li>
|
||
<li><h3><a href="#header-classes">Classes</a></h3>
|
||
<ul>
|
||
<li>
|
||
<h4><code><a title="audiocraft.models.lm.LMModel" href="#audiocraft.models.lm.LMModel">LMModel</a></code></h4>
|
||
<ul class="two-column">
|
||
<li><code><a title="audiocraft.models.lm.LMModel.call_super_init" href="#audiocraft.models.lm.LMModel.call_super_init">call_super_init</a></code></li>
|
||
<li><code><a title="audiocraft.models.lm.LMModel.compute_predictions" href="#audiocraft.models.lm.LMModel.compute_predictions">compute_predictions</a></code></li>
|
||
<li><code><a title="audiocraft.models.lm.LMModel.dump_patches" href="#audiocraft.models.lm.LMModel.dump_patches">dump_patches</a></code></li>
|
||
<li><code><a title="audiocraft.models.lm.LMModel.forward" href="#audiocraft.models.lm.LMModel.forward">forward</a></code></li>
|
||
<li><code><a title="audiocraft.models.lm.LMModel.generate" href="#audiocraft.models.lm.LMModel.generate">generate</a></code></li>
|
||
<li><code><a title="audiocraft.models.lm.LMModel.num_codebooks" href="#audiocraft.models.lm.LMModel.num_codebooks">num_codebooks</a></code></li>
|
||
<li><code><a title="audiocraft.models.lm.LMModel.special_token_id" href="#audiocraft.models.lm.LMModel.special_token_id">special_token_id</a></code></li>
|
||
<li><code><a title="audiocraft.models.lm.LMModel.training" href="#audiocraft.models.lm.LMModel.training">training</a></code></li>
|
||
</ul>
|
||
</li>
|
||
<li>
|
||
<h4><code><a title="audiocraft.models.lm.LMOutput" href="#audiocraft.models.lm.LMOutput">LMOutput</a></code></h4>
|
||
<ul class="">
|
||
<li><code><a title="audiocraft.models.lm.LMOutput.logits" href="#audiocraft.models.lm.LMOutput.logits">logits</a></code></li>
|
||
<li><code><a title="audiocraft.models.lm.LMOutput.mask" href="#audiocraft.models.lm.LMOutput.mask">mask</a></code></li>
|
||
</ul>
|
||
</li>
|
||
<li>
|
||
<h4><code><a title="audiocraft.models.lm.ScaledEmbedding" href="#audiocraft.models.lm.ScaledEmbedding">ScaledEmbedding</a></code></h4>
|
||
<ul class="two-column">
|
||
<li><code><a title="audiocraft.models.lm.ScaledEmbedding.embedding_dim" href="#audiocraft.models.lm.ScaledEmbedding.embedding_dim">embedding_dim</a></code></li>
|
||
<li><code><a title="audiocraft.models.lm.ScaledEmbedding.freeze" href="#audiocraft.models.lm.ScaledEmbedding.freeze">freeze</a></code></li>
|
||
<li><code><a title="audiocraft.models.lm.ScaledEmbedding.make_optim_group" href="#audiocraft.models.lm.ScaledEmbedding.make_optim_group">make_optim_group</a></code></li>
|
||
<li><code><a title="audiocraft.models.lm.ScaledEmbedding.max_norm" href="#audiocraft.models.lm.ScaledEmbedding.max_norm">max_norm</a></code></li>
|
||
<li><code><a title="audiocraft.models.lm.ScaledEmbedding.norm_type" href="#audiocraft.models.lm.ScaledEmbedding.norm_type">norm_type</a></code></li>
|
||
<li><code><a title="audiocraft.models.lm.ScaledEmbedding.num_embeddings" href="#audiocraft.models.lm.ScaledEmbedding.num_embeddings">num_embeddings</a></code></li>
|
||
<li><code><a title="audiocraft.models.lm.ScaledEmbedding.padding_idx" href="#audiocraft.models.lm.ScaledEmbedding.padding_idx">padding_idx</a></code></li>
|
||
<li><code><a title="audiocraft.models.lm.ScaledEmbedding.scale_grad_by_freq" href="#audiocraft.models.lm.ScaledEmbedding.scale_grad_by_freq">scale_grad_by_freq</a></code></li>
|
||
<li><code><a title="audiocraft.models.lm.ScaledEmbedding.sparse" href="#audiocraft.models.lm.ScaledEmbedding.sparse">sparse</a></code></li>
|
||
<li><code><a title="audiocraft.models.lm.ScaledEmbedding.weight" href="#audiocraft.models.lm.ScaledEmbedding.weight">weight</a></code></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</nav>
|
||
</main>
|
||
<footer id="footer">
|
||
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.5</a>.</p>
|
||
</footer>
|
||
</body>
|
||
</html>
|