Download tasks/acoustic_scene_lab/solution/reference/train.py from Tokenwave-AI/REE: direct link, hf CLI and curl.
- Browser
- Download file 3.72 kB
-
https://huggingface.co/datasets/Tokenwave-AI/REE/resolve/main/tasks/acoustic_scene_lab/solution/reference/train.py
- Command line
-
hf download hf://datasets/Tokenwave-AI/REE/tasks/acoustic_scene_lab/solution/reference/train.py
-
curl -L -o train.py https://huggingface.co/datasets/Tokenwave-AI/REE/resolve/main/tasks/acoustic_scene_lab/solution/reference/train.py
3.72 kB
| """Fit the author's fixed 10-epoch recognition checkpoint on visible labels only.""" | |
| import hashlib | |
| import json | |
| import os | |
| from pathlib import Path | |
| import sys | |
| import time | |
| import numpy as np | |
| from sklearn.preprocessing import StandardScaler | |
| sys.path.insert(0, str(Path(os.environ['CORE_DIR']) / 'interface')) | |
| from data import records, matrix | |
| from network import CLASS_CODES, windows, initialize, loss_and_grad, adam_step | |
| def train(data_root, destination): | |
| start = time.monotonic() | |
| # Keep the first manifest's row order; deduplicate repeated labeled collections. | |
| manifests = sorted(Path(data_root).glob('*/labeled.tsv')) | |
| if (Path(data_root) / 'labeled.tsv').exists(): | |
| manifests = [Path(data_root) / 'labeled.tsv'] | |
| seen, arrays, labels = {}, [], [] | |
| for manifest in manifests: | |
| for row in records(manifest.parent, 'labeled.tsv'): | |
| x = matrix(manifest.parent, row) | |
| digest = hashlib.sha256(x.tobytes()).hexdigest() | |
| key = (int(row['label']), digest) | |
| if row['id'] in seen: | |
| if seen[row['id']] != key: | |
| raise ValueError('Inconsistent repeated training record') | |
| continue | |
| seen[row['id']] = key | |
| arrays.append(x.astype(np.float64)) | |
| labels.append(int(np.flatnonzero(CLASS_CODES == key[0])[0])) | |
| if not arrays: | |
| raise ValueError('No labeled training data') | |
| scaler = StandardScaler().fit(np.concatenate(arrays)) | |
| xs, ys = [], [] | |
| for x, y in zip(arrays, labels): | |
| w = windows(scaler.transform(x)).astype(np.float32) | |
| xs.append(w) | |
| ys.append(np.full(len(w), y, dtype=np.int64)) | |
| x, y = np.concatenate(xs), np.concatenate(ys) | |
| del xs, ys, arrays | |
| rng = np.random.RandomState(1515) | |
| params = initialize(rng, len(scaler.mean_)) | |
| # Hat seeds independent dropout streams from the seeded NumPy generator. | |
| dropout_rngs = [np.random.RandomState(rng.randint(1, 10000000)) for _ in range(3)] | |
| moments = [np.zeros_like(p) for p in params] | |
| velocities = [np.zeros_like(p) for p in params] | |
| step = 0 | |
| order = np.arange(len(y)) | |
| print(json.dumps({'recordings': len(seen), 'windows': len(y), 'seed': 1515}), flush=True) | |
| for epoch in range(10): | |
| tick = time.monotonic() | |
| # Hat reshuffles the previously shuffled arrays each epoch. | |
| index = np.arange(len(y)) | |
| rng.shuffle(index) | |
| order = order[index] | |
| losses = [] | |
| for i in range(0, len(y), 100): | |
| batch = order[i:i + 100] | |
| masks = [r.binomial(1, 0.8, (len(batch), width)).astype(np.float32) / 0.8 | |
| for r, width in zip(dropout_rngs, [x.shape[1], 200, 200])] | |
| loss, grads = loss_and_grad(x[batch], y[batch], params, masks) | |
| step += 1 | |
| adam_step(params, grads, moments, velocities, step) | |
| losses.append(float(loss)) | |
| print(json.dumps({'epoch': epoch + 1, 'loss': float(np.mean(losses)), | |
| 'seconds': time.monotonic() - tick}), flush=True) | |
| destination = Path(destination) | |
| destination.mkdir(parents=True, exist_ok=True) | |
| np.savez(destination / 'model.npz', mean=scaler.mean_, scale=scaler.scale_, | |
| **{'p' + str(i): p for i, p in enumerate(params)}) | |
| metadata = {'seed': 1515, 'epochs': 10, 'batch_size': 100, 'windows': len(y), | |
| 'training_records': seen, 'seconds': time.monotonic() - start, | |
| 'source_version': '2826e26159764d550dd746469dedf9488170bb52', | |
| 'numpy': np.__version__} | |
| (destination / 'model.json').write_text(json.dumps(metadata, indent=2) + '\n') | |
| if __name__ == '__main__': | |
| train(*sys.argv[1:]) | |