Music generation: clocks, conditions and relative attention
音乐生成
Train a small conditional note model, derive all attention gradients and test what delayed audio-codeword prediction assumes.
music-generationAre you generating notes or sound?
Give a model four notes and ask it to continue. Its output might be pitches and durations, compressed-audio codewords, or eventually a waveform. These representations have different units: one note can last half a second, while an audio codeword describes one residual layer of a short sound segment. “Generate one token at a time” does not specify how much musical time each step produces.
Music generation learns to choose subsequent events given context and conditions. Symbolic representations make pitches, rhythm and instrument instructions editable. Audio representations can carry timbre and performance detail, but generally need a codec and longer message sequences. Music Transformer and MusicGen illustrate symbolic-event and audio-codeword approaches respectively. Symbolic approach Audio approach
We train an original 143-parameter conditional note model, then use a separate codeword table to explain audio interleaving. The first actually learns probabilities and samples; the second checks ordering and dependencies. Combining these examples does not make a complete MusicGen implementation. Review attention, conditional probability and neural audio codecs as prerequisites.
Specify the representation’s clock before its distribution
A sequence position does not always have a fixed duration
A fixed grid can assign each position an eighth note or fixed duration. Event representations instead describe changes through NOTE_ON, NOTE_OFF, TIME_SHIFT and VELOCITY messages. Music Transformer serializes different datasets differently. Its piano-event vocabulary has 128 note-on events, 128 note-off events, 100 time shifts and 32 velocity bins. Distance in token positions does not automatically equal distance in milliseconds. Paper section 3.1
Our smaller example uses an explicit grid. Nine output classes represent MIDI pitches [60,62,63,64,67,69,70,72] and REST. Each position lasts 0.25 seconds; a non-rest position produces a separate note at velocity 80. BOS is an additional initial input, not an output class. Repeated pitches retrigger rather than automatically merging into sustained notes. Polyphony, tempo changes and expressive velocity are unsupported.
For sequence and condition , autoregressive factorization and mean negative log likelihood are:
Teacher-forced training uses the actual past; sampling uses the generated past. Conditions can be text, melody or labels. Here they are only identifiers zero and one for two invented patterns, not evidence of understanding language or musical style. Lower loss means assigning more probability to training targets; it does not directly establish pleasing new music.
Relative attention small enough to check every parameter
Use the preceding token’s fixed four-dimensional embedding as , with BOS at step zero. Current target is excluded. Pitch embeddings contain pitch-class sine and cosine, relative register and a constant. REST and BOS have separate vectors. Embeddings are fixed, so the following gradients concern model parameters only.
Queries, keys and values have dimension four and use one head. Relative-vector table has eight rows, with distances beyond seven sharing the last row. Define :
Only is allowed; other scores are . Row softmax produces attention matrix . The divisor is . The relative term lets the same content receive different scores at different token distances, while sharing the last row loses finer distinctions among long distances. Relative-attention idea
Retain the current fixed embedding through a residual connection, then apply a linear output and condition bias:
The three projections are each 4×4; is 4×9, is 8×4, is 2×9 and has nine entries, totaling 143 parameters. There is no multi-head attention, feedforward sublayer, LayerNorm or learned embedding. Conditioning changes only logit bias. This is substantially weaker than attending to text or melody and is not a full conditional music architecture.
Differentiate from class errors back to relative vectors
Let be rowwise class softmax, the one-hot targets and the mean cross-entropy gradient with respect to logits:
Backpropagate through the output matrix into , and attention weights:
Each softmax row’s Jacobian can be evaluated using an elementwise product and subtraction of a weighted mean. Let denote the gradient of the unscaled score :
Future positions have zero . Division by two comes from the four-dimensional dot-product scaling and must not be omitted. Queries participate in both ordinary and relative dot products, giving two gradient paths:
Accumulate relative-vector gradients over every pair sharing a lag row, then use to recover the projection gradients:
The complete program finite-differences all 143 scalar parameters. It separately checks that changing target seven leaves logit rows zero through seven unchanged. Only row eight onward can receive that changed token as history. Causality checks ask whether a model sees its answer; gradient checks ask whether derivatives are correct. Gradient checking
For clarity, our code expands a relative-vector array. Music Transformer’s skew trick avoids that large array but retains a logit term. Reducing relative-tensor memory does not make the entire attention computation linear in time or space. This example does not implement that optimization. Paper section 3.4 and Table 1
Audio codewords: which dependencies does parallel prediction omit?
MusicGen encodes audio into multiple RVQ streams and predicts them using interleaving patterns. Its paper’s 32 kHz model has stride 640, producing 50 frames per second with four 2,048-entry codebooks. This differs from the preceding article’s 24 kHz EnCodec example. Flattening can condition each codebook on earlier codebooks in the same frame; parallel prediction must choose how to handle within-group dependencies. Paper sections 2–3 Pinned project description
A separate toy example places frames and codebooks in a delay table. Delay codebook by steps, using zero-based indices:
Other positions are absent, not genuine codewords. Our table has no BOS row and therefore contains rows. For four frames and three codebooks, flattening takes twelve steps, fully parallel prediction four, and the complete delay table six. Keeping only four rows discards tail codewords and should fail decoding. Pinned delay and validity code
“Fifty autoregressive steps per second” describes the steady-state main time axis. It does not eliminate finite-sequence initialization, absent positions or flushing. Read the paper and implementation with their contexts intact. We explicitly use the complete layout and make no inference-speed claim without measurement.
Predicting several positions in one group commonly uses conditional independence:
This generally differs from the group’s joint distribution. Suppose two binary codewords always agree, with (0,0) and (1,1) each having probability 0.5. Each marginal is uniform, but multiplying marginals assigns a combined 0.5 probability to (0,1) and (1,0), which are impossible under the original distribution. Reducing serial steps can therefore change the modeling assumption, not merely accelerate the same exact factorization. Parallel-factorization conditions
Train, sample and check a finite delay table
The complete program uses Python 3.12 and NumPy 1.26.4. Training consists of two original sixteen-position patterns. Condition zero repeats [0,3,4,7,4,3,0,8] twice; condition one repeats [0,2,4,6,4,2,0,8] twice. These numbers are vocabulary identifiers, not MIDI pitches themselves.
"""Original fixed-grid conditional music-token model with relative attention.
One head, fixed embeddings, learned Q/K/V/O and clipped-lag relative vectors.
No feedforward stack, text encoder, codec or real music corpus. Separate delay
layout example demonstrates finite-tail handling, not trained audio generation.
"""
import json
import numpy as np
PITCHES=[60,62,63,64,67,69,70,72,None]
def tokens(value,allow_empty=False):
x=np.asarray(value)
if allow_empty and x.size==0 and x.ndim==1:return np.array([],int)
if x.dtype.kind not in 'iu' or x.ndim!=1 or not 1<=len(x)<=64 or np.any((x<0)|(x>8)):raise ValueError('Use bounded token IDs 0 to 8')
return x.astype(int)
def initialize(seed=5):
if type(seed) is not int or not 0<=seed<2**32:raise ValueError('Invalid seed')
rng=np.random.default_rng(seed)
return {k:rng.normal(0,.15,shape) for k,shape in [('q',(4,4)),('k',(4,4)),('v',(4,4)),('o',(4,9)),('relative',(8,4)),('condition',(2,9)),('bias',(9,))]}
def parameters(p):
shapes={'q':(4,4),'k':(4,4),'v':(4,4),'o':(4,9),'relative':(8,4),'condition':(2,9),'bias':(9,)}
if not isinstance(p,dict) or p.keys()!=shapes.keys():raise ValueError('Invalid parameter fields')
result={}
for k,shape in shapes.items():
x=np.asarray(p[k])
if x.dtype.kind not in 'fiu' or x.shape!=shape or not np.isfinite(x).all() or np.any((x < -8)|(x > 8)):raise ValueError('Invalid bounded model array')
result[k]=x.astype(float)
return result
def embeddings(ids):
# Separate fixed rest and BOS vectors; MIDI pitch embeddings are not learned.
table=np.array([[np.cos((p%12)*np.pi/6),np.sin((p%12)*np.pi/6),(p-66)/12,1] if p is not None else [0,0,0,-1] for p in PITCHES]+[[0,0,1,0]])
return table[ids]
def objective(sequence,p,condition=0):
y=tokens(sequence);p=parameters(p)
if type(condition) is not int or condition not in (0,1):raise ValueError('Use condition 0 or 1')
n=len(y);x=embeddings(np.r_[9,y[:-1]]);q=x@p['q'];k=x@p['k'];v=x@p['v'];lag=np.clip(np.arange(n)[:,None]-np.arange(n)[None,:],0,7)
relative=p['relative'][lag];score=(q@k.T+np.einsum('id,ijd->ij',q,relative))/2;mask=np.triu(np.ones((n,n),bool),1);score[mask]=-np.inf
weights=np.exp(score-score.max(axis=1,keepdims=True));attention=weights/weights.sum(axis=1,keepdims=True);h=x+attention@v
logits=h@p['o']+p['condition'][condition]+p['bias'];shifted=logits-logits.max(axis=1,keepdims=True);prob=np.exp(shifted);prob/=prob.sum(axis=1,keepdims=True)
loss=float(np.mean(np.log(np.exp(shifted).sum(axis=1))-shifted[np.arange(n),y]));dz=prob.copy();dz[np.arange(n),y]-=1;dz/=n
grad={key:np.zeros_like(value) for key,value in p.items()};grad['o']=h.T@dz;grad['bias']=dz.sum(axis=0);grad['condition'][condition]=dz.sum(axis=0)
dh=dz@p['o'].T;dv=attention.T@dh;da=dh@v.T;ds=attention*(da-(attention*da).sum(axis=1,keepdims=True));ds[mask]=0;ds/=2
dq=ds@k+np.einsum('ij,ijd->id',ds,relative);dk=ds.T@q
grad['q']=x.T@dq;grad['k']=x.T@dk;grad['v']=x.T@dv
np.add.at(grad['relative'],lag.ravel(),(ds[:,:,None]*q[:,None,:]).reshape(-1,4))
return dict(loss=loss,logits=logits,probabilities=prob,attention=attention,gradient=grad)
def fit(steps=300,rate=.08):
if type(steps) is not int or not 0<=steps<=500 or type(rate) not in (int,float) or not 0<rate<=.1:raise ValueError('Invalid training settings')
sequences=[[0,3,4,7,4,3,0,8]*2,[0,2,4,6,4,2,0,8]*2];p=initialize();history=[]
for _ in range(steps):
results=[objective(y,p,c) for c,y in enumerate(sequences)];history.append(float(np.mean([r['loss'] for r in results])))
for key in p:p[key]-=rate*sum(r['gradient'][key] for r in results)/2
history.append(float(np.mean([objective(y,p,c)['loss'] for c,y in enumerate(sequences)])))
return dict(parameters=p,history=history,sequences=sequences)
def sample(p,condition=0,prefix=(),length=24,temperature=1.,seed=3):
history=tokens(prefix,True).tolist();parameters(p)
if type(length) is not int or not len(history)<=length<=64 or type(temperature) not in (int,float) or not .1<=temperature<=2 or type(seed) is not int or not 0<=seed<2**32 or type(condition) is not int or condition not in (0,1):raise ValueError('Invalid sampling settings')
rng=np.random.default_rng(seed)
while len(history)<length:
logits=objective(history+[0],p,condition)['logits'][-1]/temperature;weights=np.exp(logits-logits.max());history.append(int(rng.choice(9,p=weights/weights.sum())))
return history
def note_events(sequence,seconds_per_step=.25):
y=tokens(sequence)
if type(seconds_per_step) not in (int,float) or not .05<=seconds_per_step<=2:raise ValueError('Invalid grid duration')
result=[]
for i,t in enumerate(y):
if PITCHES[t] is not None:result.append(dict(start=i*seconds_per_step,end=(i+1)*seconds_per_step,pitch=PITCHES[t],velocity=80))
return result
def delay_pack(codes):
x=np.asarray(codes)
if x.dtype.kind not in 'iu' or x.ndim!=2 or not 1<=x.shape[0]<=16 or not 1<=x.shape[1]<=4 or np.any((x<0)|(x>7)):raise ValueError('Use frame x codebook integer IDs 0 to 7')
t,k=x.shape;layout=np.full((t+k-1,k),-1,int)
for i in range(t):
for j in range(k):layout[i+j,j]=x[i,j]
return layout
def delay_unpack(layout,frames):
x=np.asarray(layout)
if x.dtype.kind not in 'iu' or x.ndim!=2 or not 1<=x.shape[1]<=4 or type(frames) is not int or not 1<=frames<=16 or len(x)!=frames+x.shape[1]-1 or np.any((x < -1)|(x>7)):raise ValueError('Invalid delay layout')
k=x.shape[1];out=np.array([[x[i+j,j] for j in range(k)] for i in range(frames)])
if (out<0).any() or not np.array_equal(delay_pack(out),x):raise ValueError('Missing or extra code in delay layout')
return out
def clean(x):
if isinstance(x,dict):return {k:clean(v) for k,v in x.items()}
if isinstance(x,(list,tuple)):return [clean(v) for v in x]
if isinstance(x,np.ndarray):return x.tolist()
if isinstance(x,np.generic):return x.item()
return x
def demo():
trained=fit();p=trained['parameters'];samples={str(c):sample(p,c,[0],24,seed=3) for c in [0,1]};y=trained['sequences'][0];r=objective(y,p);changed=y.copy();changed[7]=(changed[7]+1)%9;other=objective(changed,p)
codes=np.arange(12).reshape(4,3)%8;layout=delay_pack(codes);probs={str(c):objective([0,0],p,c)['probabilities'][-1] for c in [0,1]}
return clean(dict(training=dict(first=trained['history'][0],last=trained['history'][-1],history=trained['history'][::10],sequences=trained['sequences']),parameters=p,parameter_count=sum(v.size for v in p.values()),attention=r['attention'],samples=samples,events={c:note_events(s) for c,s in samples.items()},condition_probabilities=probs,causal_prefix_error=float(np.max(abs(r['logits'][:8]-other['logits'][:8]))),codes=codes,delay_layout=layout,restored=delay_unpack(layout,4),parallel_counterexample=dict(true_joint=[[.5,0],[0,.5]],independent_joint=[[.25,.25],[.25,.25]],impossible_mass=.5),scope='Two invented fixed-grid token patterns, same-pattern training, no audio model or listening score. Delay table is a separate codec-order example.'))
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
With initialization seed five, 300 steps and learning rate 0.08, mean NLL over both patterns falls from about 2.157082 to 0.971923. Setting all parameters to zero gives a uniform-class baseline of . That calculable reference is not a music-quality score either. Training and reporting use the same two patterns with no held-out test split.
With sampling seed three and prefix [0], condition zero starts [0,3,0,8,0,3,3,3], whereas condition one starts [0,2,0,8,0,2,4,4]. Conditioning changes the output distribution, and the model does not mechanically reproduce the entire training sentence. This also does not demonstrate knowledge of complete musical form. Twenty-four grid positions span six seconds; rests produce no note events. The note_events output is an event list, not a MIDI file, and no listening assessment was performed.
Sampling divides logits by temperature, constrained here to 0.1 through two. Temperature changes concentration but does not guarantee improved musical coherence. For inspectability, the program recomputes the whole prefix each step and even uses the shared objective to calculate unnecessary gradients. It has no KV cache and is not suitable for speed comparisons.
One direct attention call costs approximately for and vocabulary , with relative-array storage. Recomputing successive prefixes can make total generation cost . Delay packing and unpacking cost , but are only rearrangements; their runtime is not an audio-generation model’s inference runtime.
Continuing a pattern does not establish musical structure
Comparisons can begin with simple baselines such as uniform classes or empirical adjacent-token frequencies. Also examine memorization, whether conditioning matters, long-distance structure and output diversity. This small model has no real music corpus or human ratings. Its loss teaches training mechanics and cannot support claims of professional composition ability.
A fixed grid simplifies derivation but removes tempo variation and subtle expressive timing. Note events preserve structure without necessarily specifying timbre. Audio codewords preserve more acoustic detail while increasing representation, context and decoding costs. Changing representation changes the task, not just the file extension.
MusicGen injects text and melodic conditions through components much more elaborate than our bias rows. We neither trained nor downloaded them. Readable code, accessible weights and unrestricted reuse of music data are also different claims. The project declares MIT code and CC-BY-NC 4.0 weights. We read the weight-license opening and the declaration, not a complete licensing review, and reused no weights. Code and weight declaration
Check the clock as well as the probabilities
- Identify time units. What note events does [0,8,3] produce on our 0.25-second grid? If the representation changes to NOTE_ON/TIME_SHIFT events, can token count still be multiplied by 0.25 seconds?
Answer: Position zero produces MIDI 60 from 0 to 0.25 seconds. Position one rests. Position two produces MIDI 64 from 0.5 to 0.75 seconds. Each non-rest position triggers separately, even for repeated pitches. In an event representation, TIME_SHIFT messages advance time, so token count no longer specifies a fixed duration.
- Check causality. Why must changing target leave logit rows zero through seven unchanged? Which output can first change?
Answer: Input row contains at most , and attention masks later positions. Thus first enters row eight. If prediction row seven changes, the current target leaked through the input or mask. Correct gradients cannot replace this check.
- Count the complete layout. Four frames and three codebooks use delays zero, one and two. How many rows does a complete delay table need without BOS, and what happens if only four are saved?
Answer: It needs 4+3−1 = 6 rows. Frame three’s codebook two lands in zero-based row five. Saving only four rows loses valid tail codewords and prevents full reconstruction. The example decoder rejects truncation using shape, valid-code and absent-position checks.
- Recognize independence. Two binary variables permit only (0,0) and (1,1), each with probability 0.5. How much probability does an independent-marginal model assign to impossible combinations?
Answer: Each marginal assigns 0.5 to zero and one, so all four combinations receive 0.25. The impossible pairs (0,1) and (1,0) receive 0.5 in total. Recovering the lost dependence requires within-group modeling or sufficient additional conditioning structure.
Check papers, finite layouts and licensing separately
Music Transformer’s first preprint was submitted on 2018-09-12. We read representation, relative-attention and memory-algorithm sections of v3, dated 2018-12-12. MusicGen was first submitted on 2023-06-08; we read representation, pattern, conditioning and model-setting sections of v3, dated 2024-01-30. Revision dates are not first-appearance dates. Neither paper’s listening or speed results were reproduced here. Music Transformer MusicGen
AudioCraft is pinned to 896ec7c47f5e5d1e5aa1e4b260c4405328bf009d. Pattern construction, validity masks and project documentation ground the finite-tail, configuration and declaration discussion. The code’s MIT license was read; the weight declaration does not establish that every musical asset’s license was checked. No upstream program was run, implementation copied or model downloaded. Pattern code MusicGen documentation License declaration
Make a prediction, then check
How many rows does a complete four-frame, three-codebook delay table need, without BOS?
Learning objectives
- Distinguish grid time, symbolic events and audio-codeword steps.
- Derive a conditional relative-attention model and verify all parameter gradients.
- Test strict target shifting and interpret conditional sampled sequences.
- Count finite delay tails and expose within-group independence errors.
Prerequisites & connections
Explore related knowledge →References
- Music Transformer: Generating Music with Long-Term Structure (v3)
Cheng-Zhi Anna Huang; Ashish Vaswani; Jakob Uszkoreit; Noam Shazeer; Ian Simon; Curtis Hawthorne; Andrew M. Dai; Matthew D. Hoffman; Monica Dinculescu; Douglas Eck · 2018 - Simple and Controllable Music Generation (v3)
Jade Copet; Felix Kreuk; Itai Gat; Tal Remez; David Kant; Gabriel Synnaeve; Yossi Adi; Alexandre Défossez · 2023 - AudioCraft delay patterns and validity masks at 896ec7c
AudioCraft contributors - MusicGen documentation at 896ec7c
AudioCraft contributors - AudioCraft README licensing declarations at 896ec7c
AudioCraft contributors
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-13 · Single AI author checked specified Music Transformer v3 and MusicGen v3 sections and fixed AudioCraft pattern code. Ten paired equations and four explained exercises; all 143 derivatives of an original conditional symbolic model, causal shift, 300 training steps, finite delayed codebook tail and independence counterexample. No audio model or listening evaluation.
- Verified all143 central-difference gradients, causal shifted inputs, conditional probabilities,300-step same-pattern NLL,6-second symbolic event lists,4-frame/3-codebook six-step layout and0.5 impossible mass under marginal independence.
- Four computed SVGs bind exact bilingual MDX. The two-topic group passed11 numeric/encoding checks and12 isolated language/width cases with four fallback fonts; four representative final screenshots inspected by the AI author. Condition-prefix labeling corrected against actual shifted-input code with original figures preserved. Literal-prose AST checked before freezing. Full article browser acceptance is separate; no human peer review.
Source locations checked:
- Music Transformer: Generating Music with Long-Term Structure (v3) · Read sections 3.1–3.4 and selected Table 1/skew passages; visually inspected PDF pages 3–4. v3 dated 2018-12-12, first submitted 2018-09-12. No listening or speed reproduction.
- Simple and Controllable Music Generation (v3) · Read sections 2.1–2.4 and selected 3.1 settings; visually inspected PDF pages 3–4. v3 dated 2024-01-30, first submitted 2023-06-08. No model, data license or listening benchmark reproduced.
- AudioCraft delay patterns and validity masks at 896ec7c · Read lines 330–357 delay construction and 134–156 validity filtering. Our finite table has no BOS row; no upstream Torch execution.
- MusicGen documentation at 896ec7c · Read lines 1–36 for architecture and opening usage/data self-description. No complete documentation, training-data audit, weights or sample listening.
- AudioCraft README licensing declarations at 896ec7c · Read model entry pointers and lines 75–76 code/weight license declarations. Code MIT text read fully; LICENSE_weights opening only read, not a full licensing review.
Related topics