-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstreaming_report.py
268 lines (192 loc) · 7.14 KB
/
streaming_report.py
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
"""[markdown]
# Streaming
## Original (Streaming)
"""
# streaming.orig
"""[markdown]
## Reconstruction (Streaming)
"""
# streaming.recon
"""[markdown]
## Events
"""
# streaming.scatter
n_samples = 2 ** 17
samples_per_event = 2048
# this is cut in half since we'll mask out the second half of encoder activations
n_events = (n_samples // samples_per_event) // 2
context_dim = 32
# the samplerate, in hz, of the audio signal
samplerate = 22050
# derived, the total number of seconds of audio
n_seconds = n_samples / samplerate
transform_window_size = 2048
transform_step_size = 256
n_frames = n_samples // transform_step_size
from argparse import ArgumentParser
from typing import Dict
import torch
from torch import nn
from conjure import S3Collection, \
conjure_article, CitationComponent, AudioComponent, \
CompositeComponent, Logger, ScatterPlotComponent
from data import get_one_audio_segment
from iterativedecomposition import Model as IterativeDecompositionModel
from modules.eventgenerators.overfitresonance import OverfitResonanceModel
import numpy as np
from typing import Tuple
from sklearn.manifold import TSNE
from modules import max_norm
from util import device
remote_collection_name = 'streaming-report-v1'
def to_numpy(x: torch.Tensor):
return x.data.cpu().numpy()
# thanks to https://discuss.pytorch.org/t/how-do-i-check-the-number-of-parameters-of-a-model/4325/9
def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
def process_events(
vectors: torch.Tensor,
times: torch.Tensor,
total_seconds: float) -> Tuple:
# compute each event time in seconds
positions = torch.argmax(times, dim=-1, keepdim=True) / times.shape[-1]
times = [float(x) for x in (positions * total_seconds).view(-1).data.cpu().numpy()]
# normalize event vectors
normalized = vectors.data.cpu().numpy().reshape((-1, context_dim))
normalized = normalized - normalized.min(axis=0, keepdims=True)
normalized = normalized / (normalized.max(axis=0, keepdims=True) + 1e-8)
# map normalized event vectors into single dimension
tsne = TSNE(n_components=2)
points = tsne.fit_transform(normalized)
proj = np.random.uniform(0, 1, (2, 3))
colors = points @ proj
colors -= colors.min()
colors /= (colors.max() + 1e-8)
colors *= 255
colors = colors.astype(np.uint8)
colors = [f'rgb({c[0]} {c[1]} {c[2]})' for c in colors]
# t = np.array(times) / total_seconds
# points = np.concatenate([points.reshape((-1, 1)), t.reshape((-1, 1))], axis=-1)[:, ::-1]
return points, times, colors
def load_model(wavetable_device: str = 'gpu') -> nn.Module:
hidden_channels = 512
model = IterativeDecompositionModel(
in_channels=1024,
hidden_channels=hidden_channels,
resonance_model=OverfitResonanceModel(
n_noise_filters=64,
noise_expressivity=4,
noise_filter_samples=128,
noise_deformations=32,
instr_expressivity=4,
n_events=1,
n_resonances=4096,
n_envelopes=64,
n_decays=64,
n_deformations=64,
n_samples=n_samples,
n_frames=n_frames,
samplerate=samplerate,
hidden_channels=hidden_channels,
wavetable_device=device,
fine_positioning=True,
fft_resonance=True
)).to(device)
with open('iterativedecomposition8.dat', 'rb') as f:
model.load_state_dict(torch.load(f))
# model = model.eval()
print('Total parameters', count_parameters(model))
print('Encoder parameters', count_parameters(model.encoder))
print('Decoder parameters', count_parameters(model.resonance))
return model
# def scatterplot_section(logger: Logger, events, points, times, colors) -> ScatterPlotComponent:
# events = events.view(-1, n_samples)
#
# events = {f'event{i}': events[i: i + 1, :] for i in range(events.shape[0])}
#
# scatterplot_srcs = []
#
# event_components = {}
# for k, v in events.items():
# _, e = logger.log_sound(k, v)
# scatterplot_srcs.append(e.public_uri)
# event_components[k] = AudioComponent(e.public_uri, height=35, controls=False)
#
# scatterplot_component = ScatterPlotComponent(
# scatterplot_srcs,
# width=500,
# height=500,
# radius=0.3,
# points=points,
# times=times,
# colors=colors, )
#
# return scatterplot_component
def streaming_section(logger: Logger) -> CompositeComponent:
model = load_model()
samples = get_one_audio_segment(n_samples * 8, samplerate).view(1, 1, -1).to(device)
# samples = max_norm(samples)
with torch.no_grad():
recon, event_vectors, times, events = model.streaming(samples, return_event_vectors=True)
# recon = model.streaming(samples, return_event_vectors=False)
recon = max_norm(recon)
# points, times, colors = process_events(event_vectors, times, n_seconds)
# scatter = scatterplot_section(logger, events, points, times, colors)
_, orig = logger.log_sound(key='streamingorig', audio=samples)
orig = AudioComponent(orig.public_uri, height=100, controls=True, scale=4, samples=1024)
_, recon = logger.log_sound(key='streamingrecon', audio=recon)
recon = AudioComponent(recon.public_uri, height=100, controls=True, scale=4, samples=1024)
# TODO: audio timeline version
return CompositeComponent(
orig=orig,
recon=recon,
# scatter=scatter
)
"""[markdown]
# Notes
This blog post is generated from a
[Python script](https://github.com/JohnVinyard/matching-pursuit/blob/main/v3blogpost.py) using
[conjure](https://github.com/JohnVinyard/conjure).
"""
def demo_page_dict() -> Dict[str, any]:
print(f'Generating article...')
remote = S3Collection(
remote_collection_name, is_public=True, cors_enabled=True)
logger = Logger(remote)
print('Creating streaming section')
streaming = streaming_section(logger)
citation = CitationComponent(
tag='johnvinyarditerativedecompositionv3',
author='Vinyard, John',
url='https://blog.cochlea.xyz/iterative-decomposition-v7.html',
header='Iterative Decomposition V7',
year='2024',
)
return dict(
streaming=streaming,
citation=citation
)
def generate_demo_page():
display = demo_page_dict()
conjure_article(
__file__,
'html',
title='Streaming Iterative Decomposition Model',
**display)
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_argument('--clear', action='store_true')
parser.add_argument('--list', action='store_true')
args = parser.parse_args()
if args.list:
remote = S3Collection(
remote_collection_name, is_public=True, cors_enabled=True)
print(remote)
print('Listing stored keys')
for key in remote.iter_prefix(start_key=b'', prefix=b''):
print(key)
if args.clear:
remote = S3Collection(
remote_collection_name, is_public=True, cors_enabled=True)
remote.destroy(prefix=b'')
generate_demo_page()