Spaces:
Sleeping
Sleeping
File size: 9,002 Bytes
9c7e38e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 | """
Sampling and bar-level constraints for music generation.
"""
from typing import Dict
import numpy as np
import torch
import torch.nn.functional as F # noqa: F401
import config
# =========================
# Simple music-theory rules
# =========================
# C major scale degrees within one octave (0–11):
# C, D, E, F, G, A, B
C_MAJOR_INDICES = [0, 2, 4, 5, 7, 9, 11]
def enforce_scale(
bar: Dict[str, np.ndarray],
allowed_indices=C_MAJOR_INDICES,
) -> Dict[str, np.ndarray]:
"""
Zero out melodic pitches not in the allowed scale for each melodic family.
Args:
bar: dict with keys "strings", "woodwinds", "brass", "perc".
allowed_indices: list of pitch indices (0–11) allowed in the scale.
Returns:
bar with non-scale pitches zeroed for melodic families.
"""
mask = np.zeros((config.PITCHES_MELODIC,), dtype=np.float32)
mask[allowed_indices] = 1.0
for key in ["strings", "woodwinds", "brass"]:
grid = bar[key] # [T, 12]
bar[key] = grid * mask # broadcast over time
return bar
def limit_notes_per_step(
bar: Dict[str, np.ndarray],
max_notes_per_step: int = 4,
) -> Dict[str, np.ndarray]:
"""
For each melodic family and time step, restrict to at most max_notes_per_step notes.
This reduces dense vertical clusters and produces simpler chords.
"""
for key in ["strings", "woodwinds", "brass"]:
grid = bar[key] # [T, pitches]
T, P = grid.shape
for t in range(T):
on_indices = np.where(grid[t] > 0.5)[0]
if len(on_indices) > max_notes_per_step:
# Keep the first few; zero out the rest
to_keep = on_indices[:max_notes_per_step]
mask = np.zeros_like(grid[t])
mask[to_keep] = 1.0
grid[t] = mask
bar[key] = grid
return bar
def count_total_notes(
bar: Dict[str, np.ndarray],
) -> int:
"""
Count total number of "on" notes across all instrument families in a bar.
"""
total = 0
for key in ["strings", "woodwinds", "brass", "perc"]:
total += np.count_nonzero(bar[key] > 0.5)
return int(total)
def emphasize_strong_beats(
bar: Dict[str, np.ndarray],
) -> Dict[str, np.ndarray]:
"""
Encourage notes on strong beats (0, 2, 4, 6) for melodic families.
If a strong beat has no note in a family, randomly turn one on.
"""
strong_steps = [0, 2, 4, 6]
for key in ["strings", "woodwinds", "brass"]:
grid = bar[key] # [T, 12]
T, P = grid.shape
for t in strong_steps:
if t >= T:
continue
if np.sum(grid[t] > 0.5) == 0:
p = np.random.randint(0, P)
grid[t, p] = 1.0
bar[key] = grid
return bar
# =========================
# Logit → binary grid sampling
# =========================
def sample_binary_from_logits(
logits: torch.Tensor,
temperature: float = 1.0,
top_k: int = 0,
) -> torch.Tensor:
"""
Sample binary activations from logits for one instrument.
Args:
logits: [T, P] tensor (time steps, pitches).
temperature: Temperature for scaling; >1.0 → more random.
top_k: If >0, keep only top_k logits per time step before sampling.
Returns:
activations: [T, P] tensor of 0/1 (float).
"""
if temperature <= 0:
raise ValueError("temperature must be > 0")
# Scale by temperature
scaled_logits = logits / temperature
# Optional top-k per time step
if top_k > 0:
# Clamp k so it never exceeds number of pitches for this instrument
num_pitches = scaled_logits.shape[-1]
k = min(top_k, num_pitches)
values, indices = torch.topk(scaled_logits, k=k, dim=-1)
mask = torch.full_like(scaled_logits, float("-inf"))
mask.scatter_(-1, indices, values)
scaled_logits = mask
# Convert to probabilities
probs = torch.sigmoid(scaled_logits) # [T, P]
# Bernoulli sampling
bernoulli_samples = torch.bernoulli(probs)
return bernoulli_samples
def sample_bar_from_logits_dict(
logits_dict: Dict[str, torch.Tensor],
temperature: float = 1.0,
top_k: int = 0,
) -> Dict[str, np.ndarray]:
"""
Sample a full bar (all instruments) from per-instrument logits.
Args:
logits_dict:
"strings": [T, 12],
"woodwinds": [T, 12],
"brass": [T, 12],
"perc": [T, 3],
where T should be config.STEPS_PER_BAR.
temperature: Temperature for sampling.
top_k: top-k filter per instrument per time step.
Returns:
Dict of numpy arrays with shape [STEPS_PER_BAR, pitches] and 0/1 values.
"""
bar_grids: Dict[str, np.ndarray] = {}
for name, logits in logits_dict.items():
# Expect [T, P]
if logits.dim() == 3:
logits = logits.squeeze(0) # [T, P]
assert logits.shape[0] == config.STEPS_PER_BAR, f"{name}: wrong T"
samples = sample_binary_from_logits(
logits=logits,
temperature=temperature,
top_k=top_k,
) # [T, P]
bar_grids[name] = samples.cpu().numpy().astype(np.float32)
return bar_grids
# =========================
# Bar similarity and resampling
# =========================
def bar_similarity(
bar1: Dict[str, np.ndarray],
bar2: Dict[str, np.ndarray],
) -> float:
"""
Compute normalized similarity between two bars.
Both bars are dicts:
"strings": [STEPS_PER_BAR, 12],
"woodwinds": [STEPS_PER_BAR, 12],
"brass": [STEPS_PER_BAR, 12],
"perc": [STEPS_PER_BAR, 3],
Similarity is defined as:
1 - (Hamming distance / total_cells)
"""
flat1_list = []
flat2_list = []
for key in ["strings", "woodwinds", "brass", "perc"]:
g1 = bar1[key].astype(np.float32)
g2 = bar2[key].astype(np.float32)
flat1_list.append(g1.reshape(-1))
flat2_list.append(g2.reshape(-1))
flat1 = np.concatenate(flat1_list)
flat2 = np.concatenate(flat2_list)
total_cells = flat1.size
if total_cells == 0:
return 0.0
diff = np.abs(flat1 - flat2)
hamming = np.count_nonzero(diff)
similarity = 1.0 - (hamming / float(total_cells))
return float(similarity)
def count_active_families(
bar: Dict[str, np.ndarray],
) -> int:
"""
Count how many instrument families have at least one active note in the bar.
"""
active_count = 0
for key in ["strings", "woodwinds", "brass", "perc"]:
grid = bar[key]
if np.any(grid > 0.5):
active_count += 1
return active_count
def resample_bar_if_needed(
prev_bar: Dict[str, np.ndarray],
logits_dict: Dict[str, torch.Tensor],
temperature: float,
top_k: int,
similarity_threshold: float = config.BAR_SIMILARITY_THRESHOLD,
max_attempts: int = config.MAX_RESAMPLE_ATTEMPTS_PER_BAR,
min_active_families: int = config.MIN_ACTIVE_FAMILIES_PER_BAR,
min_notes_per_bar: int = 2,
max_notes_per_step: int = 4,
) -> Dict[str, np.ndarray]:
"""
Sample a bar from logits, enforcing:
- Not too similar to prev_bar (if prev_bar is provided).
- At least min_active_families have notes.
- At least min_notes_per_bar total notes.
- At most max_notes_per_step notes per step per melodic family.
"""
attempt = 0
best_bar = None
best_similarity = -1.0
while attempt < max_attempts:
attempt += 1
# Sample raw bar
candidate_bar = sample_bar_from_logits_dict(
logits_dict=logits_dict,
temperature=temperature,
top_k=top_k,
)
# Apply theory rules
candidate_bar = enforce_scale(candidate_bar)
candidate_bar = emphasize_strong_beats(candidate_bar)
candidate_bar = limit_notes_per_step(candidate_bar, max_notes_per_step=max_notes_per_step)
# Activity and density
active = count_active_families(candidate_bar)
total_notes = count_total_notes(candidate_bar)
# If no prev_bar, only activity + density constraints
if prev_bar is None:
if active >= min_active_families and total_notes >= min_notes_per_bar:
return candidate_bar
if best_bar is None:
best_bar = candidate_bar
continue
# Compare to previous bar
sim = bar_similarity(candidate_bar, prev_bar)
# Track best candidate for fallback
if sim > best_similarity:
best_similarity = sim
best_bar = candidate_bar
# Check constraints: not too similar, enough active families, enough notes
if (sim <= similarity_threshold) and (active >= min_active_families) and (total_notes >= min_notes_per_bar):
return candidate_bar
# Fallback
return best_bar |