|
| 1 | +import os |
| 2 | +import torch |
| 3 | +import numpy as np |
| 4 | +from SoundCodec.codec import list_codec, load_codec |
| 5 | + |
| 6 | +def calculate_metrics(): |
| 7 | + print(f"{'Codec':<40} | {'BPS (kbps)':<10} | {'TPS':<10}") |
| 8 | + print("-" * 65) |
| 9 | + |
| 10 | + os.environ['CUDA_VISIBLE_DEVICES'] = '' |
| 11 | + # Monkeypatch to ensure no MPS is used |
| 12 | + if hasattr(torch.backends, 'mps'): |
| 13 | + torch.backends.mps.is_available = lambda: False |
| 14 | + torch.backends.mps.is_built = lambda: False |
| 15 | + device = 'cpu' |
| 16 | + |
| 17 | + codecs = list_codec() |
| 18 | + |
| 19 | + # Create specific test inputs |
| 20 | + duration = 1.0 # 1 second |
| 21 | + |
| 22 | + for name in codecs: |
| 23 | + try: |
| 24 | + # Skip problematic ones for now if they crash, but try to run all |
| 25 | + if name in ['bigcodec_1k', 'dac_24k', 'dac_44k', 's3tokenizer_v1']: |
| 26 | + # We know these are problematic on this env, but let's try or skip |
| 27 | + # For now, let's catch exceptions |
| 28 | + pass |
| 29 | + |
| 30 | + metric_name = name |
| 31 | + codec = load_codec(name) |
| 32 | + |
| 33 | + # Determine sampling rate |
| 34 | + sr = getattr(codec, 'sampling_rate', 16000) |
| 35 | + if sr is None: sr = 16000 |
| 36 | + |
| 37 | + # Generate 1 second of silence/noise |
| 38 | + # standard shape is usually (1, T) or (T,) |
| 39 | + audio_data = np.random.randn(int(sr * duration)).astype(np.float32) |
| 40 | + |
| 41 | + data_item = { |
| 42 | + 'audio': { |
| 43 | + 'array': audio_data, |
| 44 | + 'sampling_rate': sr |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + # Extract unit |
| 49 | + # Move to device if necessary? Base codecs usually handle 'cpu' default or auto-device |
| 50 | + # But let's force cpu for safety to avoid MPS issues seen earlier |
| 51 | + if hasattr(codec, 'config'): |
| 52 | + # Some codecs might need explicit config call if not in __init__ |
| 53 | + pass |
| 54 | + |
| 55 | + if hasattr(codec, 'device'): |
| 56 | + # Force CPU for calculation safety |
| 57 | + codec.device = 'cpu' |
| 58 | + if hasattr(codec, 'model'): |
| 59 | + codec.model.to('cpu') |
| 60 | + |
| 61 | + with torch.no_grad(): |
| 62 | + extracted = codec.extract_unit(data_item) |
| 63 | + unit = extracted.unit |
| 64 | + |
| 65 | + # Calculate TPS |
| 66 | + # unit shape is typically (n_quantizers, T) or (T, n_quantizers) or just (T) |
| 67 | + # We need to find the time dimension. |
| 68 | + # Usually the longest dimension that is not the quantizer count (which is usually small, e.g. 4, 8, 32, 128) |
| 69 | + # WavTokenizer: (1, T) -> T is tokens |
| 70 | + # Encodec: (n_q, T) |
| 71 | + |
| 72 | + shape = unit.shape |
| 73 | + # Heuristic to find Time dimension |
| 74 | + # Usually T is roughly sr / stride |
| 75 | + # codebook dim is usually small < 128 |
| 76 | + |
| 77 | + if len(shape) == 1: |
| 78 | + frames = shape[0] |
| 79 | + num_quantizers = 1 |
| 80 | + elif len(shape) == 2: |
| 81 | + if shape[0] > shape[1]: # (T, Q) |
| 82 | + frames = shape[0] |
| 83 | + num_quantizers = shape[1] |
| 84 | + else: # (Q, T) |
| 85 | + frames = shape[1] |
| 86 | + num_quantizers = shape[0] |
| 87 | + elif len(shape) == 3: |
| 88 | + # (B, Q, T) or (B, T, Q) -> assume B=1 from extract_unit usually returning squeezed |
| 89 | + # But extract_unit usually returns (Q, T) or (T) |
| 90 | + # Let's assume (Q, T) mostly |
| 91 | + frames = max(shape) |
| 92 | + num_quantizers = shape[0] * shape[1] * shape[2] / frames # Simple check |
| 93 | + else: |
| 94 | + frames = 0 |
| 95 | + num_quantizers = 0 |
| 96 | + |
| 97 | + tps = frames / duration |
| 98 | + |
| 99 | + # Calculate BPS |
| 100 | + # Depends on codebook size (bits per token) |
| 101 | + # Most codecs use 1024 (10 bits) or 2048 (11 bits) or similar. |
| 102 | + # However, exact bitrate is often defined as: |
| 103 | + # Bitrate = FrameRate * NumQuantizers * BitsPerCode |
| 104 | + # But "BitsPerCode" depends on the model. |
| 105 | + |
| 106 | + # ALTERNATIVE: Use the metric name to guess for some, but user wants calculation. |
| 107 | + # We can't easily know the codebook size from just the unit tensor (it contains indices). |
| 108 | + # But we can assume standard codebook sizes: |
| 109 | + # Encodec: 1024 (10 bits) |
| 110 | + # DAC: 1024 (10 bits) |
| 111 | + # FunCodec: usually 1024? |
| 112 | + |
| 113 | + # Actually, calculating BPS from *tensor size* is tricky without knowing vocab size. |
| 114 | + # But we can print TPS for sure. |
| 115 | + # For BPS, checking the paper/config is safer if we can't inspect the model. |
| 116 | + |
| 117 | + # Let's print TPS first, and try to deduce BPS if possible. |
| 118 | + # For Encodec, we know bits = n_q * 10. |
| 119 | + # BPS (kbps) = TPS * n_q * 10 / 1000 |
| 120 | + |
| 121 | + print(f"{metric_name:<40} | {'?':<10} | {tps:<10.2f} (Shape: {shape})") |
| 122 | + |
| 123 | + except Exception as e: |
| 124 | + print(f"{name:<40} | ERROR | {e}") |
| 125 | + |
| 126 | +if __name__ == "__main__": |
| 127 | + calculate_metrics() |
0 commit comments