音乐生成:时钟、条件与相对注意力
Music generation
训练小型条件音符模型,推导注意力完整梯度,检验音频码字延迟预测的假设。
music-generation生成的是音符,还是声音?
给模型四个音符,让它续写。输出可以是一串音高与时长,也可以是压缩音频的码字,还可以最终变成波形。三种表示的单位不同:一个音符可能持续半秒,一个音频码字却只描述一小段声音的某层残差。“一次生成一个token”并没有告诉你一次生成了多少音乐时间。
音乐生成(music generation)学习在上下文和条件下选择后续事件。符号表示便于编辑音高、节奏和乐器指令;音频表示可以携带音色与演奏细节,但通常需要编解码器和更长的消息序列。Music Transformer与MusicGen分别提供了符号事件和音频码字路线的具体例子。符号路线 音频路线
本篇训练一个143参数的原创条件音符模型,再用一张独立码字表解释音频交错。前者真的学习概率并采样,后者只检查排列与依赖;不会把二者拼起来叫完整MusicGen。先修可参照注意力、条件概率和神经音频编解码。
先写清表示的时钟,再写生成分布
序列中的一格不总是同样长
固定网格可以让每个位置表示八分音符或一个固定时长。事件表示则用NOTE_ON、NOTE_OFF、TIME_SHIFT、VELOCITY等消息表达变化。Music Transformer针对不同数据采用不同序列化方式,其钢琴事件词表包含128种开音、128种关音、100种时间移动与32种力度档位;token位置的差,不自动等于同样的毫秒差。原论文§3.1
本例选择更小、明确的固定网格。9个输出类别是MIDI音高[60,62,63,64,67,69,70,72]和REST;每格0.25秒,非休止格产生一个独立音符,力度恒为80。另设BOS起始输入,它不在输出词表中。重复同一音高会重新发音,不自动连接成长音;不支持复音、变速或表达性力度。
设序列为,条件为。自回归分解及平均负对数似然为:
教师强制训练用真实过去作为条件,采样用已经生成的过去。条件可以是文字、旋律或标签;本例只有两个虚构模式的编号0、1,不能把编号说成模型理解了自然语言或音乐风格。损失降低说明给训练目标分配的概率提高,不能直接证明新乐段动听。
一个小到能核验每个参数的相对注意力模型
用前一个token的固定4维嵌入作为,第0步用BOS;当前目标不出现在输入里。音高嵌入包含音高类的正弦/余弦、相对音区和常量,REST与BOS有独立向量。嵌入固定不训练,所以下面的梯度只针对模型参数。
查询、键、值均为4维,单个头;相对向量表有8行,距离超过7时共用最后一行。令:
只允许,其余score设为;每行softmax得到注意力矩阵。分母为。相对项让相同内容在不同token距离下获得不同分数,但远距离共用一行会失去更细的距离区别。相对注意力思想
当前固定嵌入通过残差保留,再接线性输出和条件偏置:
各4×4,为4×9,为8×4,为2×9,为9维,总计143参数。本例没有多头、前馈子层、LayerNorm或学习式嵌入。条件只改变logit偏置;它远弱于对文字或旋律做交叉注意力,不应被称为完整的条件音乐架构。
从分类误差一路求回相对向量
设是逐行类别softmax,是独热目标,平均交叉熵对logit的导数为:
随后从输出矩阵回传到、与注意力权重:
softmax每行的雅可比可写成一个乘法与一个加权均值扣除。记为对未缩放分数的梯度:
未来位置的为0。除以2来自4维点积的缩放,不能漏掉。查询同时参与普通点积与相对项,因而有两条梯度路径:
最后对所有共享同一距离行的配对累加相对向量梯度,再通过回到三个投影矩阵:
完整程序对143个标量参数逐一做中央差分检查。还检查改变目标第7项不影响logit第0至7行:只有从第8行开始,改过的token才进入过去。这个因果检查和梯度检查分别回答“有没有偷看答案”和“有没有正确求导”。梯度检查
本例直接展开相对向量数组,便于看清公式。Music Transformer的skew技巧避免这种大数组,但仍有的logit项;不能把相对张量内存的改进写成整个注意力线性时间或空间。这里没有实现该优化。原论文§3.4与Table 1
音频码字:并行预测省下了哪些依赖?
MusicGen把音频编成多层RVQ码字,再按模式交错预测。其论文中的32 kHz模型总步长640,得到50帧/s,四层码本各2048项;这不同于前篇的24 kHz EnCodec实例。平铺可以在同一帧内依次看过前面的码本,整帧并行则必须决定怎样处理同组依赖。原论文§2–3 固定项目说明
一个独立小例子把帧、个码本放进延迟表:第个码本延迟步,零起点时为:
其余位置是缺位,不是真实码字。本例不含BOS行,所以布局长度为。4帧、3码本:平铺12步,完全并行4步,完整延迟表6步。若只保留4行,会丢掉收尾码字;解码器应拒绝这样的表。固定延迟与有效位代码
“每秒50个自回归步”描述稳态主时间轴,不能据此忽略有限序列的预填充、缺位和收尾。原论文与代码的上下文应分开读。这里明确选择完整布局,不推算未实际测量的推理速度。
同一组内并行预测常用条件独立分解:
它一般不等于该组的联合分布。假设两个二元码字总相等,(0,0)和(1,1)各占0.5。两边缘都是均匀分布,独立相乘却给(0,1)、(1,0)合计0.5概率;模型会产生原分布中根本不存在的组合。因此减少串行步骤可能改变建模假设,不只是把同一精确分解加速。并行分解条件
训练、采样,再核对一张有限延迟表
完整程序使用Python 3.12、NumPy 1.26.4。训练集是两条原创模式,各16格:条件0使用[0,3,4,7,4,3,0,8]重复两次,条件1使用[0,2,4,6,4,2,0,8]重复两次。数字是词表编号,不是MIDI音高本身。
"""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))
初始化种子5,300步、学习率0.08,两模式平均NLL从约2.157082降到0.971923。把所有参数置0的均匀分类基线为;这个可计算参照也不是音乐质量评分。训练和报告使用同两条模式,没有留出测试集。
固定采样种子3、前缀[0]时,条件0的前8格为[0,3,0,8,0,3,3,3],条件1为[0,2,0,8,0,2,4,4]。条件改变了输出分布,模型没有机械复制整个训练句子;这也不证明它学会了完整曲式。24格占6秒网格时间,休止格不生成音符事件;note_events返回事件列表,不是一个MIDI文件,也没有在这里试听。
采样按温度缩放logit,温度范围限制为0.1至2。温度改变分布的集中程度,并不保证增强音乐连贯性。程序为便于复核每一步重算整个前缀,甚至通过同一objective同时计算了不需要的梯度;它没有KV缓存,不用于速度比较。
单次长度的直接注意力约,其中、,相对向量数组占空间。逐步重算前缀使生成整体可达。延迟表的打包/解包为,但只是排列,不能用它的耗时冒充音频生成模型推理。
会续写一个模式,不等于掌握音乐结构
比较模型时,可以先用均匀类别分布、统计相邻token频率等简单基线。需要同时检查训练数据记忆、条件是否起作用、长距离结构与生成多样性。这个小模型没有真实曲库或人评,损失只能用于理解训练,不支持“达到专业作曲水平”的判断。
固定网格方便推导,却抹去了速度变化和细微演奏时差。音符事件保留结构,也未必指定具体音色;音频码字保留更多声学细节,却增加表示、长上下文和解码成本。改变表示会改变任务,而不仅是换一种文件后缀。
MusicGen的文字条件和旋律条件采用了比本例复杂得多的编码与注入方式。本篇没有训练或下载那些组件;代码可读、权重可获取与音乐数据可任意复用也不是同一回事。项目声明代码MIT、权重CC-BY-NC 4.0;本次只读权重许可开头和说明,没有做完整许可审查或复用权重。代码与权重说明
概率对了,时钟也要对
- 找出时间单位。 本例输出[0,8,3],每格0.25秒,产生哪些音符事件?若换成NOTE_ON/TIME_SHIFT事件序列,还能用token数量乘0.25秒吗?
答案:第0格发MIDI60,0至0.25秒;第1格休止;第2格发MIDI64,0.5至0.75秒。不论音高重复与否,每个非休止格独立发音。事件表示中时间由TIME_SHIFT等消息推进,token数不再等于固定时长。
- 检查因果性。 修改目标,为什么本例logit第0至7行必须不变?哪个输出最早可能变化?
答案:第行输入最多含,注意力又屏蔽更后位置,因此最早进入第8行。若第7行预测已经改变,说明当前目标泄漏到输入或掩码有误;梯度正确也不能替代这个检查。
- 算完整布局。 4帧、3码本,延迟分别为0、1、2。无BOS的完整延迟表有几行?只保存4行会怎样?
答案:共有4+3−1=6行。第3帧第2码本落在零起点第5行;只保存4行会丢失尾部有效码字,无法完整还原。本例解码器用形状、有效码和缺位规则拒绝截断表。
- 识别独立假设。 两个二元变量只有(0,0)、(1,1),各0.5。独立边缘模型对原本不可能的组合分配多少概率?
答案:每个边缘的0/1概率均0.5,因此四个组合各0.25,(0,1)与(1,0)合计0.5。完整联合分布里的相关性丢失了;要恢复它,需要组内依赖建模或其他足够的条件结构。
把模型论文、有限布局和许可分开核对
Music Transformer首个预印本在2018-09-12提交,本篇读取v3(2018-12-12)的表示、相对注意力与内存算法段;MusicGen首投2023-06-08,读取v3(2024-01-30)的表示、模式、条件及模型设置。修订日期不是方法首次出现日期。两篇的听感/速度成绩没有在此复现。Music Transformer MusicGen
AudioCraft固定在896ec7c47f5e5d1e5aa1e4b260c4405328bf009d;模式构造、有效位mask和项目说明用于核对有限收尾、模型设置与声明范围。代码MIT已核读,权重说明不代表所有音乐素材许可已核实。本文没有运行上游、复制实现或下载模型。模式代码 MusicGen说明 许可声明
先判断,再看解释
4帧、3码本的完整延迟表,无BOS时需要几行?
学习目标
- 区分网格时间、符号事件与音频码字步数。
- 推导条件相对注意力模型并验证全部参数梯度。
- 检查严格目标移位并解释条件采样序列。
- 计算有限延迟收尾并识别组内独立假设的误差。
先修与延伸
查看知识关联图 →参考文献
- 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
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(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.
- 核验全部143中央差分梯度、因果移位输入、条件概率、300步同模式NLL、6秒符号事件、4帧3码本的6步延迟表及边缘独立下.5不可能质量。
- 四张计算SVG绑定真实双语程序;本组11项数值/编码检查、12组语言/宽度及四字体检查通过,AI作者实际查看四张最终代表截图;条件前缀标注按真实移位输入修正并保留原图。冻结前检查普通正文AST;完整文章页面验收另记,不称人工同行审校。
核对的来源位置:
- 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.
相关主题