Audio, speech, music, and audio-language systems · Streaming speech and multimodal audio systems · AUD068 · Model
Qwen2-Audio
An audio-language model accepting speech and other audio, with optional textual instructions, and generating text responses. It supports voice-instruction and audio-analysis interaction styles.
In CodeSplash
Documented in the Academy only. There's no Set up button.
- Availability
- Explained here
- Code example
- Component demo, not a trained model
- Who ran it
- CodeSplash's run and the reference's record
- CodeSplash's run
- The reference's example ran in Python and R here, and they agree.
- The reference's record
- Python: Ran in the reference's review. The report doesn't record which version of the code ran. R: Reviewed but not run: R wasn't available to the reference's authors.
Purpose
An audio-language model accepting speech and other audio, with optional textual instructions, and generating text responses. It supports voice-instruction and audio-analysis interaction styles. Its audio input capability must not be mistaken for built-in waveform speech output; that distinction separates it from audio-generating omni systems.
Question / hypotheses
Can an audio-conditioned language model follow spoken or textual instructions while grounding its answer in the supplied sound? This is predictive/generative modeling, with no inherent H0/H1; benchmark comparisons require a separately designed inference protocol.
Architecture / computational structure
A speech/audio encoder maps acoustic inputs into representations consumed with text by a large language model. Audio-language alignment, instruction tuning, and preference training shape different aspects of behavior. Use the released model’s exact processor rather than treating an arbitrary waveform array as ordinary text tokens.
Assumptions
Audio order, sample rate, preprocessing, and chat-template placeholders must match the checkpoint. Spoken instructions and background events may compete for attention. A fluent response can rely on language priors and add unsupported details; audio-grounded correctness requires evidence-based evaluation beyond answer fluency.
Formula / computational definition
Supervised audio-conditioned generation minimizes , where is the encoded audio and an optional text instruction. Preference optimization is an additional training stage; the displayed cross entropy is not a complete account of that preference objective.
Parameters and notation
Learned parameters include audio encoder, modality projection/adapter, and language-model embeddings/attention/heads. Hyperparameters include audio length handling, instruction mixture, adaptation scope, optimizer schedule, and decoding temperature/output length. Changing instruction prompts is inference conditioning rather than learned-parameter fine-tuning.
Fitting, fine-tuning, and adaptation
A practical adaptation plan starts with the connector or language-model adapters and freezes the acoustic encoder, then compares selective unfreezing with smaller backbone rates. Mask prompt/padding positions correctly in supervised targets. Balance transcription, audio-event, and reasoning examples, and hold out speakers/recordings to prevent apparent gains from acoustic memorization.
How to use and calibrate
Evaluate transcription, sound classification/captioning, instruction following, and question answering separately. Include nonspeech, ambiguous recordings, missing-evidence prompts, and wrong-audio controls to test grounding. Report accuracy/content metrics, generation latency, and abstention behavior where the task permits uncertainty.
Example application
Answer questions about licensed environmental clips and spoken commands, then manually verify which answer claims are supported by the recording.
Interpretation / pitfalls
Watch out
Python: the official repository documents Transformers Qwen2AudioForConditionalGeneration with AutoProcessor and its chat template. R: reticulate to those same components. The example demonstrates target-token cross entropy and a confidence proxy’s limitations; it does not load the model or prove that a response is acoustically grounded.
Python and R code examples (dependencies/validation)
Load the shared audio helper setup. These are deterministic component illustrations, not full-model implementations. Python/NumPy: executed successfully. R/base R: not executed because Rscript was unavailable. No model weights were downloaded.
Python and R
The reference's own programs, shown as written. A component demo shows one central piece of the method; it doesn't train a full model.
Component demo, not a trained model — These are deterministic component illustrations, not full-model implementations.
Shared setup for this chapter
"""Shared helpers for educational audio objective/architecture components.
This file and all AUD snippets use NumPy only. They do not load trained networks.
"""
import itertools
import numpy as np
def ce(p, y):
p=np.asarray(p, float); y=np.asarray(y, int)
return float(-np.log(np.clip(p[np.arange(len(y)),y],1e-12,1)).mean())
def bce(p,y):
p=np.clip(np.asarray(p,float),1e-12,1-1e-12); y=np.asarray(y,float)
return float(-(y*np.log(p)+(1-y)*np.log(1-p)).mean())
def mse(a,b): return float(np.mean((np.asarray(a)-np.asarray(b))**2))
def l1(a,b): return float(np.mean(np.abs(np.asarray(a)-np.asarray(b))))
def softmax(a):
a=np.asarray(a,float); a=a-a.max(axis=-1,keepdims=True)
z=np.exp(a); return z/z.sum(axis=-1,keepdims=True)
def contrast(a,b,tau=.2):
a=np.asarray(a,float); b=np.asarray(b,float)
a=a/np.linalg.norm(a,axis=1,keepdims=True); b=b/np.linalg.norm(b,axis=1,keepdims=True)
s=a@b.T/tau; y=np.arange(len(a))
return (ce(softmax(s),y)+ce(softmax(s.T),y))/2
def collapse(path):
merged=[v for i,v in enumerate(path) if i==0 or v!=path[i-1]]
return tuple(v for v in merged if v!=0)
def ctc_prob(p,target):
p=np.asarray(p,float)
return sum(np.prod([p[t,j] for t,j in enumerate(path)])
for path in itertools.product(range(p.shape[1]), repeat=len(p))
if collapse(path)==tuple(target))
def pit_mse(estimate,reference):
estimate=np.asarray(estimate); reference=np.asarray(reference)
return min(mse(estimate,reference[list(p)]) for p in itertools.permutations(range(len(reference))))
def cosine(a,b):
a=np.asarray(a,float); b=np.asarray(b,float)
return float(a@b/(np.linalg.norm(a)*np.linalg.norm(b)))
# Shared deterministic fixtures; token labels are zero-based in Python.
P=np.array([[.1,.7,.2],[.2,.2,.6],[.6,.2,.2]])
y=np.array([1,2,0])
A=np.array([[1.,0.],[0.,1.],[1.,1.]])
B=np.array([[.9,.1],[.1,.9],[.8,1.]])
s=np.sin(np.arange(32)*.4)
x=s+.1*np.cos(np.arange(32)*.9)
# AUD068: educational component
token_loss=ce(P,y); token_confidence=float(P.max(1).mean())
result={"target_token_loss":token_loss,"mean_max_token_probability":token_confidence} # not grounding confidence
print(result)
Component demo, not a trained model — These are deterministic component illustrations, not full-model implementations.
Shared setup for this chapter
# Shared educational helpers. These do not load trained neural networks.
# Base R only; labels/indexes are one-based, with blank token 1 for CTC.
ce <- function(p,y) -mean(log(pmax(pmin(p[cbind(seq_along(y),y)],1),1e-12)))
bce <- function(p,y) {
p <- pmax(pmin(p,1-1e-12),1e-12)
-mean(y*log(p)+(1-y)*log(1-p))
}
mse <- function(a,b) mean((a-b)^2)
l1 <- function(a,b) mean(abs(a-b))
softmax <- function(a) {
if (is.null(dim(a))) a <- matrix(a,nrow=1)
z <- exp(a-apply(a,1,max)); z/rowSums(z)
}
contrast <- function(a,b,tau=.2) {
a <- a/sqrt(rowSums(a*a)); b <- b/sqrt(rowSums(b*b))
z <- a %*% t(b)/tau; y <- seq_len(nrow(a))
(ce(softmax(z),y)+ce(softmax(t(z)),y))/2
}
collapse <- function(path) {
merged <- path[c(TRUE,diff(path)!=0)]
merged[merged!=1]
}
ctc_prob <- function(p,target) {
paths <- expand.grid(rep(list(seq_len(ncol(p))),nrow(p)))
total <- 0
for (i in seq_len(nrow(paths))) {
path <- as.integer(unlist(paths[i,],use.names=FALSE))
if (identical(collapse(path),as.integer(target))) {
total <- total+prod(p[cbind(seq_len(nrow(p)),path)])
}
}
total
}
pit_mse <- function(estimate,reference) {
stopifnot(nrow(reference)==2) # This teaching helper handles exactly two sources.
min(mse(estimate,reference),mse(estimate,reference[2:1,,drop=FALSE]))
}
cosine <- function(a,b) sum(a*b)/sqrt(sum(a*a)*sum(b*b))
P <- matrix(c(.1,.7,.2,.2,.2,.6,.6,.2,.2),nrow=3,byrow=TRUE)
y <- c(2L,3L,1L)
A <- matrix(c(1,0,0,1,1,1),nrow=3,byrow=TRUE)
B <- matrix(c(.9,.1,.1,.9,.8,1),nrow=3,byrow=TRUE)
s <- sin((0:31)*.4)
x <- s+.1*cos((0:31)*.9)
# AUD068: requires shared R setup
result <- c(target_token_loss=ce(P,y),mean_max_token_probability=mean(apply(P,1,max))) # not grounding confidence
print(result)
Sources
- Primary source 1arxiv.org
- Primary source 2github.com
From the CodeSplash reference, entry AUD068.