Skip to content

Commit eeb2cb2

Browse files
authored
Add opt-in attention scale and MIDI event controls (#1376)
1 parent ce8b317 commit eeb2cb2

5 files changed

Lines changed: 57 additions & 6 deletions

File tree

‎include/engine/framework/midi/midi_file.h‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,17 @@ struct MidiNote {
1616
double offset_seconds = 0.0;
1717
int pitch = 0;
1818
std::string track_name;
19+
// Zero retains MidiFileOptions::velocity for existing callers.
20+
int velocity = 0;
1921
};
2022

2123
struct MidiFileOptions {
2224
int ticks_per_beat = 480;
2325
int tempo_us_per_beat = 500000;
2426
int velocity = 100;
27+
// Already-decoded events: keep supplied durations/overlaps, including drums.
28+
// Invalid times are rejected rather than repaired.
29+
bool preserve_note_events = false;
2530
};
2631

2732
// Raw note positions preserve metrical timing; no tempo conversion or cleanup.

‎include/engine/framework/modules/attention/scaled_dot_product_attention.h‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ struct ScaledDotProductAttentionConfig {
2626
ScaledDotProductAttentionLowering lowering = ScaledDotProductAttentionLowering::Explicit;
2727
ggml_prec precision = GGML_PREC_F32;
2828
AttentionCausality causality = AttentionCausality::NonCausal;
29+
// Override 1/sqrt(head_dim), e.g. when Q/K have zero-padded head widths.
30+
std::optional<float> scale = std::nullopt;
2931
};
3032

3133
class ScaledDotProductAttentionModule {

‎src/framework/midi/midi_file.cpp‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ struct NoteEvent {
2222
int velocity = 0;
2323
int pitch = 0;
2424
std::string track_name;
25+
int midi_velocity = 0;
2526
};
2627

2728
void require_u7(int value, const char * name) {
@@ -94,11 +95,15 @@ int event_key_program(const NoteEvent & event) {
9495
return event.is_drum ? kDrumProgram : event.program;
9596
}
9697

97-
std::vector<NoteEvent> note_events_from_notes(const std::vector<MidiNote> & notes) {
98+
std::vector<NoteEvent> note_events_from_notes(const std::vector<MidiNote> & notes, bool preserve) {
9899
std::vector<NoteEvent> events;
99100
events.reserve(notes.size() * 2);
100101
for (const auto & note : notes) {
101102
require_u7(note.pitch, "MIDI note pitch");
103+
require_u7(note.velocity, "MIDI note velocity");
104+
if (preserve && (!std::isfinite(note.onset_seconds) || !std::isfinite(note.offset_seconds) ||
105+
note.onset_seconds < 0 || note.offset_seconds <= note.onset_seconds))
106+
throw std::runtime_error("MIDI note times must be finite, non-negative and have positive duration");
102107
if (!note.is_drum) {
103108
require_u7(note.program, "MIDI program");
104109
}
@@ -109,11 +114,12 @@ std::vector<NoteEvent> note_events_from_notes(const std::vector<MidiNote> & note
109114
1,
110115
note.pitch,
111116
note.track_name,
117+
note.velocity,
112118
});
113119
events.push_back(NoteEvent{
114120
note.is_drum,
115121
note.program,
116-
note.is_drum ? note.onset_seconds + kMinimumNoteDurationSeconds : note.offset_seconds,
122+
note.is_drum && !preserve ? note.onset_seconds + kMinimumNoteDurationSeconds : note.offset_seconds,
117123
0,
118124
note.pitch,
119125
note.track_name,
@@ -310,8 +316,8 @@ std::vector<std::byte> write_standard_midi_file(
310316
}
311317
require_u7(options.velocity, "MIDI velocity");
312318

313-
const auto clean_notes = clean_midi_notes(notes);
314-
const auto events = note_events_from_notes(clean_notes);
319+
const auto clean_notes = options.preserve_note_events ? notes : clean_midi_notes(notes);
320+
const auto events = note_events_from_notes(clean_notes, options.preserve_note_events);
315321

316322
std::vector<std::byte> meta_track;
317323
append_u8(meta_track, 0x00);
@@ -368,7 +374,7 @@ std::vector<std::byte> write_standard_midi_file(
368374
append_varlen(track, static_cast<uint32_t>(delta_tick));
369375
append_u8(track, static_cast<uint8_t>((event.velocity > 0 ? 0x90 : 0x80) | channels[key]));
370376
append_u8(track, static_cast<uint8_t>(event.pitch));
371-
append_u8(track, static_cast<uint8_t>(event.velocity > 0 ? options.velocity : 0));
377+
append_u8(track, static_cast<uint8_t>(event.velocity > 0 ? (event.midi_velocity ? event.midi_velocity : options.velocity) : 0));
372378
}
373379
for (const int key : track_order) {
374380
auto & track = tracks[key];

‎src/framework/modules/attention/scaled_dot_product_attention.cpp‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -313,7 +313,7 @@ core::TensorValue ScaledDotProductAttentionModule::build(
313313
v_heads.shape.dims[3] != config_.head_dim) {
314314
throw std::runtime_error("ScaledDotProductAttention flash lowering requires equal Q/K/V widths");
315315
}
316-
const float scale = 1.0F / std::sqrt(static_cast<float>(config_.head_dim));
316+
const float scale = config_.scale.value_or(1.0F / std::sqrt(static_cast<float>(config_.head_dim)));
317317
switch (config_.lowering) {
318318
case ScaledDotProductAttentionLowering::Explicit:
319319
return build_explicit(ctx, q_heads, k_heads, v_heads, attention_mask, scale, config_.precision, config_.causality, score_scale);

‎tests/unittests/test_midi_file.cpp‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,11 @@
55
#include "test_assert.h"
66

77
#include <chrono>
8+
#include <array>
89
#include <cstddef>
910
#include <cstdint>
1011
#include <iostream>
12+
#include <limits>
1113
#include <stdexcept>
1214
#include <string>
1315
#include <vector>
@@ -287,6 +289,41 @@ void test_reader_rejects_malformed_data() {
287289
}
288290
}
289291

292+
void test_preserved_events_and_velocities() {
293+
const std::vector<engine::midi::MidiNote> notes{
294+
{false, 0, 0.0, 1.0, 60, "piano", 37},
295+
{false, 0, 0.5, 0.75, 60, "piano", 91},
296+
{true, 0, 0.25, 0.35, 36, "drums", 53},
297+
};
298+
engine::midi::MidiFileOptions options;
299+
options.preserve_note_events = true;
300+
const auto tracks = parse_midi(engine::midi::write_standard_midi_file(notes, options));
301+
require_eq(tracks.size(), size_t{3}, "preserved track count");
302+
// 120 BPM / 480 PPQ gives 960 ticks/second, independently of the writer.
303+
require_eq(tracks[1].events.size(), size_t{4}, "overlapping same-pitch events");
304+
const std::array<uint32_t, 4> ticks{0, 480, 720, 960};
305+
for (size_t i = 0; i < ticks.size(); ++i)
306+
require_eq(tracks[1].events[i].tick, ticks[i], "preserved overlap tick");
307+
require_eq(tracks[1].events[0].b, uint8_t{37}, "first predicted velocity");
308+
require_eq(tracks[1].events[1].b, uint8_t{91}, "second predicted velocity");
309+
require_eq(tracks[2].events[0].b, uint8_t{53}, "drum predicted velocity");
310+
require_eq(tracks[2].events[0].tick, uint32_t{240}, "drum onset");
311+
require_eq(tracks[2].events[1].tick, uint32_t{336}, "preserved 100 ms drum duration");
312+
313+
// Demonstrate the existing cleanup cannot serialize these events intact.
314+
const auto cleaned = parse_midi(engine::midi::write_standard_midi_file(notes));
315+
require_eq(cleaned[1].events[1].status, uint8_t{0x80}, "default trims earlier overlap");
316+
require_eq(cleaned[2].events[1].tick, uint32_t{250}, "default still uses 10 ms drums");
317+
for (const double offset : {0.0, -1.0, std::numeric_limits<double>::infinity()}) {
318+
auto invalid = notes;
319+
invalid[0].offset_seconds = offset;
320+
bool rejected = false;
321+
try { engine::midi::write_standard_midi_file(invalid, options); }
322+
catch (const std::runtime_error &) { rejected = true; }
323+
require(rejected, "preserve mode must reject invalid event times");
324+
}
325+
}
326+
290327
} // namespace
291328

292329
int main(int argc, char ** argv) {
@@ -299,6 +336,7 @@ int main(int argc, char ** argv) {
299336
test_empty_midi_has_header_and_tempo_track();
300337
test_multi_track_notes_and_drums();
301338
test_overlap_is_trimmed_before_serializing();
339+
test_preserved_events_and_velocities();
302340
test_reader_roundtrip();
303341
test_reader_running_status_and_overlapping_notes();
304342
test_reader_keeps_tick_timing_across_tempo_changes();

0 commit comments

Comments
 (0)