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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Codec Inversion Worker — runs on cheap GPUs to invert JL clips.
|
| 2 |
+
|
| 3 |
+
Usage: python inversion_worker.py --shard-id 0 --num-shards 15
|
| 4 |
+
Each worker processes 806/num_shards clips.
|
| 5 |
+
|
| 6 |
+
Requires: Code2Wav checkpoint at /workspace/code2wav/ (downloaded from HF)
|
| 7 |
+
Outputs: /workspace/inverted_codes/{clip_idx}.pt files
|
| 8 |
+
"""
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
import torch.nn.functional as F
|
| 12 |
+
import numpy as np
|
| 13 |
+
import soundfile as sf
|
| 14 |
+
import os, time, json, gc, argparse, sys
|
| 15 |
+
|
| 16 |
+
ts = lambda: time.strftime("%I:%M:%S %p")
|
| 17 |
+
|
| 18 |
+
# ============================================================
|
| 19 |
+
# Audio loss (proven in test6b)
|
| 20 |
+
# ============================================================
|
| 21 |
+
class AudioLoss(nn.Module):
|
| 22 |
+
def __init__(self, sr=24000, n_mels=80,
|
| 23 |
+
n_ffts=[512, 1024, 2048], hop_lengths=[128, 256, 512]):
|
| 24 |
+
super().__init__()
|
| 25 |
+
self.sr = sr
|
| 26 |
+
self.n_mels = n_mels
|
| 27 |
+
self.n_ffts = n_ffts
|
| 28 |
+
self.hop_lengths = hop_lengths
|
| 29 |
+
self.mel_fbanks = nn.ParameterList()
|
| 30 |
+
for n_fft in n_ffts:
|
| 31 |
+
fbank = self._mel_filterbank(n_fft, n_mels, sr)
|
| 32 |
+
self.mel_fbanks.append(nn.Parameter(fbank, requires_grad=False))
|
| 33 |
+
|
| 34 |
+
def _mel_filterbank(self, n_fft, n_mels, sr):
|
| 35 |
+
fmin, fmax = 0, sr // 2
|
| 36 |
+
mel_low = 2595 * np.log10(1 + fmin / 700)
|
| 37 |
+
mel_high = 2595 * np.log10(1 + fmax / 700)
|
| 38 |
+
mel_points = np.linspace(mel_low, mel_high, n_mels + 2)
|
| 39 |
+
hz_points = 700 * (10 ** (mel_points / 2595) - 1)
|
| 40 |
+
bins = np.floor((n_fft + 1) * hz_points / sr).astype(int)
|
| 41 |
+
fbank = np.zeros((n_mels, n_fft // 2 + 1))
|
| 42 |
+
for m in range(1, n_mels + 1):
|
| 43 |
+
f_left, f_center, f_right = bins[m-1], bins[m], bins[m+1]
|
| 44 |
+
for k in range(f_left, f_center):
|
| 45 |
+
if f_center > f_left:
|
| 46 |
+
fbank[m-1, k] = (k - f_left) / (f_center - f_left)
|
| 47 |
+
for k in range(f_center, f_right):
|
| 48 |
+
if f_right > f_center:
|
| 49 |
+
fbank[m-1, k] = (f_right - k) / (f_right - f_center)
|
| 50 |
+
return torch.FloatTensor(fbank)
|
| 51 |
+
|
| 52 |
+
def _stft(self, audio, n_fft, hop_length):
|
| 53 |
+
audio = audio.reshape(-1)
|
| 54 |
+
pad = n_fft // 2
|
| 55 |
+
audio_pad = F.pad(audio, (pad, pad), mode='constant', value=0.0)
|
| 56 |
+
window = torch.hann_window(n_fft, device=audio.device)
|
| 57 |
+
stft = torch.stft(audio_pad, n_fft=n_fft, hop_length=hop_length,
|
| 58 |
+
win_length=n_fft, window=window, return_complex=True)
|
| 59 |
+
return stft
|
| 60 |
+
|
| 61 |
+
def forward(self, predicted, target):
|
| 62 |
+
pred = predicted.squeeze()
|
| 63 |
+
targ = target.squeeze()
|
| 64 |
+
total_loss = 0
|
| 65 |
+
for i, (n_fft, hop) in enumerate(zip(self.n_ffts, self.hop_lengths)):
|
| 66 |
+
fbank = self.mel_fbanks[i]
|
| 67 |
+
pred_stft = self._stft(pred, n_fft, hop)
|
| 68 |
+
targ_stft = self._stft(targ, n_fft, hop)
|
| 69 |
+
pred_mag = pred_stft.abs()
|
| 70 |
+
targ_mag = targ_stft.abs()
|
| 71 |
+
if pred_mag.dim() == 2:
|
| 72 |
+
pred_mag = pred_mag.unsqueeze(0)
|
| 73 |
+
targ_mag = targ_mag.unsqueeze(0)
|
| 74 |
+
min_frames = min(pred_mag.shape[-1], targ_mag.shape[-1])
|
| 75 |
+
pred_mag = pred_mag[..., :min_frames]
|
| 76 |
+
targ_mag = targ_mag[..., :min_frames]
|
| 77 |
+
stft_l1 = F.l1_loss(pred_mag, targ_mag)
|
| 78 |
+
stft_log = F.l1_loss(torch.log(pred_mag.clamp(min=1e-5)),
|
| 79 |
+
torch.log(targ_mag.clamp(min=1e-5)))
|
| 80 |
+
fbank_dev = fbank.to(pred_mag.device)
|
| 81 |
+
pred_mel = torch.log(torch.matmul(fbank_dev, pred_mag).clamp(min=1e-5))
|
| 82 |
+
targ_mel = torch.log(torch.matmul(fbank_dev, targ_mag).clamp(min=1e-5))
|
| 83 |
+
mel_l1 = F.l1_loss(pred_mel, targ_mel)
|
| 84 |
+
total_loss = total_loss + stft_l1 + stft_log + mel_l1
|
| 85 |
+
return total_loss / len(self.n_ffts)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# ============================================================
|
| 89 |
+
# STE Code2Wav forwards
|
| 90 |
+
# ============================================================
|
| 91 |
+
def deterministic_code2wav_forward(code2wav, logits, tau=1.0, hard=True):
|
| 92 |
+
batch, nq, seq_len, cb_size = logits.shape
|
| 93 |
+
probs = F.softmax(logits / tau, dim=-1)
|
| 94 |
+
if hard:
|
| 95 |
+
index = probs.argmax(dim=-1, keepdim=True)
|
| 96 |
+
hard_onehot = torch.zeros_like(probs).scatter_(-1, index, 1.0)
|
| 97 |
+
probs = hard_onehot - probs.detach() + probs
|
| 98 |
+
embed_dim = code2wav.code_embedding.weight.shape[1]
|
| 99 |
+
cb_weights = code2wav.code_embedding.weight
|
| 100 |
+
soft_embeds = []
|
| 101 |
+
for q in range(nq):
|
| 102 |
+
q_embed = cb_weights[q * cb_size : (q + 1) * cb_size]
|
| 103 |
+
q_soft = probs[:, q]
|
| 104 |
+
q_result = torch.matmul(q_soft, q_embed.to(q_soft.dtype))
|
| 105 |
+
soft_embeds.append(q_result)
|
| 106 |
+
soft_embeds = torch.stack(soft_embeds, dim=1)
|
| 107 |
+
hidden = soft_embeds.mean(1)
|
| 108 |
+
hidden = code2wav.pre_transformer(inputs_embeds=hidden).last_hidden_state
|
| 109 |
+
hidden = hidden.permute(0, 2, 1)
|
| 110 |
+
for blocks in code2wav.upsample:
|
| 111 |
+
for block in blocks:
|
| 112 |
+
hidden = block(hidden)
|
| 113 |
+
wav = hidden
|
| 114 |
+
for block in code2wav.decoder:
|
| 115 |
+
wav = block(wav)
|
| 116 |
+
return wav.clamp(min=-1, max=1)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def soft_code2wav_forward(code2wav, logits, tau=1.0, hard=False):
|
| 120 |
+
batch, nq, seq_len, cb_size = logits.shape
|
| 121 |
+
soft = F.gumbel_softmax(logits, tau=tau, hard=hard, dim=-1)
|
| 122 |
+
embed_dim = code2wav.code_embedding.weight.shape[1]
|
| 123 |
+
cb_weights = code2wav.code_embedding.weight
|
| 124 |
+
soft_embeds = []
|
| 125 |
+
for q in range(nq):
|
| 126 |
+
q_embed = cb_weights[q * cb_size : (q + 1) * cb_size]
|
| 127 |
+
q_soft = soft[:, q]
|
| 128 |
+
q_result = torch.matmul(q_soft, q_embed.to(q_soft.dtype))
|
| 129 |
+
soft_embeds.append(q_result)
|
| 130 |
+
soft_embeds = torch.stack(soft_embeds, dim=1)
|
| 131 |
+
hidden = soft_embeds.mean(1)
|
| 132 |
+
hidden = code2wav.pre_transformer(inputs_embeds=hidden).last_hidden_state
|
| 133 |
+
hidden = hidden.permute(0, 2, 1)
|
| 134 |
+
for blocks in code2wav.upsample:
|
| 135 |
+
for block in blocks:
|
| 136 |
+
hidden = block(hidden)
|
| 137 |
+
wav = hidden
|
| 138 |
+
for block in code2wav.decoder:
|
| 139 |
+
wav = block(wav)
|
| 140 |
+
return wav.clamp(min=-1, max=1)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
# ============================================================
|
| 144 |
+
# Single clip inversion
|
| 145 |
+
# ============================================================
|
| 146 |
+
def invert_clip(c2w, target_tensor, loss_fn, config, total_upsample,
|
| 147 |
+
warmup_steps=100, ste_steps=400):
|
| 148 |
+
"""Invert a single audio clip to codec tokens."""
|
| 149 |
+
seq_len = len(target_tensor) // total_upsample
|
| 150 |
+
if seq_len < 2:
|
| 151 |
+
return None, float('inf'), 0.0
|
| 152 |
+
|
| 153 |
+
device = target_tensor.device
|
| 154 |
+
|
| 155 |
+
logits = torch.zeros(1, config.num_quantizers, seq_len, config.codebook_size,
|
| 156 |
+
device=device, dtype=torch.float32)
|
| 157 |
+
logits += torch.randn_like(logits) * 0.01
|
| 158 |
+
logits.requires_grad_(True)
|
| 159 |
+
|
| 160 |
+
# Phase 1: Soft warmup
|
| 161 |
+
optimizer = torch.optim.AdamW([logits], lr=0.1, weight_decay=0.0)
|
| 162 |
+
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
|
| 163 |
+
optimizer, T_max=warmup_steps, eta_min=0.01)
|
| 164 |
+
|
| 165 |
+
for step in range(warmup_steps):
|
| 166 |
+
optimizer.zero_grad()
|
| 167 |
+
wav_out = soft_code2wav_forward(c2w, logits, tau=1.0, hard=False)
|
| 168 |
+
loss = loss_fn(wav_out, target_tensor)
|
| 169 |
+
loss.backward()
|
| 170 |
+
torch.nn.utils.clip_grad_norm_([logits], max_norm=10.0)
|
| 171 |
+
optimizer.step()
|
| 172 |
+
scheduler.step()
|
| 173 |
+
|
| 174 |
+
best_logits = logits.detach().clone()
|
| 175 |
+
|
| 176 |
+
# Phase 2: STE refinement
|
| 177 |
+
logits = best_logits.clone().requires_grad_(True)
|
| 178 |
+
optimizer = torch.optim.AdamW([logits], lr=0.05, weight_decay=0.0)
|
| 179 |
+
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
|
| 180 |
+
optimizer, T_max=ste_steps, eta_min=0.001)
|
| 181 |
+
|
| 182 |
+
best_loss = float('inf')
|
| 183 |
+
for step in range(ste_steps):
|
| 184 |
+
optimizer.zero_grad()
|
| 185 |
+
wav_out = deterministic_code2wav_forward(c2w, logits, tau=1.0, hard=True)
|
| 186 |
+
loss = loss_fn(wav_out, target_tensor)
|
| 187 |
+
loss.backward()
|
| 188 |
+
torch.nn.utils.clip_grad_norm_([logits], max_norm=5.0)
|
| 189 |
+
optimizer.step()
|
| 190 |
+
scheduler.step()
|
| 191 |
+
|
| 192 |
+
if loss.item() < best_loss:
|
| 193 |
+
best_loss = loss.item()
|
| 194 |
+
best_logits = logits.detach().clone()
|
| 195 |
+
|
| 196 |
+
final_codes = best_logits.argmax(dim=-1)
|
| 197 |
+
|
| 198 |
+
# Cosine similarity
|
| 199 |
+
with torch.no_grad():
|
| 200 |
+
wav_final = c2w(final_codes)
|
| 201 |
+
pred = wav_final.squeeze()
|
| 202 |
+
targ = target_tensor.squeeze()
|
| 203 |
+
n_fft, hop = 1024, 256
|
| 204 |
+
window = torch.hann_window(n_fft, device=pred.device)
|
| 205 |
+
p_stft = torch.stft(pred, n_fft=n_fft, hop_length=hop, win_length=n_fft,
|
| 206 |
+
window=window, return_complex=True)
|
| 207 |
+
t_stft = torch.stft(targ, n_fft=n_fft, hop_length=hop, win_length=n_fft,
|
| 208 |
+
window=window, return_complex=True)
|
| 209 |
+
p_mag = p_stft.abs().flatten()
|
| 210 |
+
t_mag = t_stft.abs()[:, :p_stft.shape[1]].flatten()
|
| 211 |
+
min_len = min(len(p_mag), len(t_mag))
|
| 212 |
+
cosine = F.cosine_similarity(p_mag[:min_len].unsqueeze(0),
|
| 213 |
+
t_mag[:min_len].unsqueeze(0)).item()
|
| 214 |
+
|
| 215 |
+
return final_codes, best_loss, cosine
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
# ============================================================
|
| 219 |
+
# Main
|
| 220 |
+
# ============================================================
|
| 221 |
+
def main():
|
| 222 |
+
parser = argparse.ArgumentParser()
|
| 223 |
+
parser.add_argument('--shard-id', type=int, required=True)
|
| 224 |
+
parser.add_argument('--num-shards', type=int, required=True)
|
| 225 |
+
parser.add_argument('--total-clips', type=int, default=806)
|
| 226 |
+
parser.add_argument('--output-dir', type=str, default='/workspace/inverted_codes')
|
| 227 |
+
parser.add_argument('--hf-repo', type=str, default='msrcam/claudia_voice_dataset')
|
| 228 |
+
parser.add_argument('--c2w-repo', type=str, default='msrcam/qwen3-omni-code2wav')
|
| 229 |
+
args = parser.parse_args()
|
| 230 |
+
|
| 231 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 232 |
+
|
| 233 |
+
print(f"[{ts()}] === Codec Inversion Worker {args.shard_id}/{args.num_shards} ===")
|
| 234 |
+
|
| 235 |
+
# Calculate this shard's clip range
|
| 236 |
+
clips_per_shard = args.total_clips // args.num_shards
|
| 237 |
+
start_idx = args.shard_id * clips_per_shard
|
| 238 |
+
end_idx = start_idx + clips_per_shard if args.shard_id < args.num_shards - 1 else args.total_clips
|
| 239 |
+
my_clips = list(range(start_idx, end_idx))
|
| 240 |
+
print(f" Processing clips {start_idx}-{end_idx-1} ({len(my_clips)} clips)")
|
| 241 |
+
|
| 242 |
+
# Load Code2Wav from standalone checkpoint
|
| 243 |
+
print(f"[{ts()}] Loading Code2Wav from {args.c2w_repo}...")
|
| 244 |
+
|
| 245 |
+
try:
|
| 246 |
+
# Try loading from HF repo (standalone checkpoint)
|
| 247 |
+
from huggingface_hub import hf_hub_download
|
| 248 |
+
c2w_path = hf_hub_download(args.c2w_repo, "code2wav_state_dict.pt", repo_type="model")
|
| 249 |
+
config_path = hf_hub_download(args.c2w_repo, "code2wav_config.json", repo_type="model")
|
| 250 |
+
model_config_dir = hf_hub_download(args.c2w_repo, "config.json", repo_type="model")
|
| 251 |
+
model_config_dir = os.path.dirname(model_config_dir)
|
| 252 |
+
|
| 253 |
+
from transformers import AutoConfig, Qwen3OmniMoeForConditionalGeneration
|
| 254 |
+
|
| 255 |
+
config_full = AutoConfig.from_pretrained(model_config_dir, trust_remote_code=True)
|
| 256 |
+
|
| 257 |
+
# Create model shell on meta device (no actual weights loaded)
|
| 258 |
+
with torch.device("meta"):
|
| 259 |
+
model = Qwen3OmniMoeForConditionalGeneration._from_config(config_full)
|
| 260 |
+
|
| 261 |
+
c2w = model.code2wav
|
| 262 |
+
|
| 263 |
+
# Load real Code2Wav weights
|
| 264 |
+
state_dict = torch.load(c2w_path, map_location="cuda:0", weights_only=True)
|
| 265 |
+
c2w.load_state_dict(state_dict, assign=True)
|
| 266 |
+
c2w = c2w.to("cuda:0")
|
| 267 |
+
|
| 268 |
+
del model
|
| 269 |
+
print(f" Code2Wav loaded from standalone checkpoint")
|
| 270 |
+
|
| 271 |
+
except Exception as e:
|
| 272 |
+
print(f" Standalone load failed ({e}), falling back to full model load...")
|
| 273 |
+
from transformers import Qwen3OmniMoeForConditionalGeneration
|
| 274 |
+
model = Qwen3OmniMoeForConditionalGeneration.from_pretrained(
|
| 275 |
+
"/workspace/models/qwen3-omni",
|
| 276 |
+
torch_dtype=torch.float32,
|
| 277 |
+
device_map="cuda:0",
|
| 278 |
+
trust_remote_code=True,
|
| 279 |
+
attn_implementation="eager",
|
| 280 |
+
)
|
| 281 |
+
c2w = model.code2wav
|
| 282 |
+
del model.thinker, model.talker
|
| 283 |
+
torch.cuda.empty_cache()
|
| 284 |
+
|
| 285 |
+
c2w.eval()
|
| 286 |
+
for p in c2w.parameters():
|
| 287 |
+
p.requires_grad_(False)
|
| 288 |
+
|
| 289 |
+
config = c2w.config
|
| 290 |
+
total_upsample = int(np.prod(config.upsample_rates + config.upsampling_ratios))
|
| 291 |
+
print(f" codebook={config.codebook_size}, quantizers={config.num_quantizers}, "
|
| 292 |
+
f"upsample={total_upsample}")
|
| 293 |
+
print(f" GPU memory: {torch.cuda.memory_allocated()/1e9:.1f}GB")
|
| 294 |
+
|
| 295 |
+
loss_fn = AudioLoss(sr=24000).to("cuda:0")
|
| 296 |
+
|
| 297 |
+
# Download and process clips
|
| 298 |
+
from huggingface_hub import hf_hub_download
|
| 299 |
+
|
| 300 |
+
results = []
|
| 301 |
+
t_start = time.time()
|
| 302 |
+
|
| 303 |
+
for i, clip_idx in enumerate(my_clips):
|
| 304 |
+
clip_name = f"{clip_idx:05d}"
|
| 305 |
+
out_path = f"{args.output_dir}/{clip_name}.pt"
|
| 306 |
+
|
| 307 |
+
# Skip if already done
|
| 308 |
+
if os.path.exists(out_path):
|
| 309 |
+
print(f" [{i+1}/{len(my_clips)}] {clip_name} — already done, skipping")
|
| 310 |
+
continue
|
| 311 |
+
|
| 312 |
+
try:
|
| 313 |
+
# Download clip
|
| 314 |
+
wav_path = hf_hub_download(args.hf_repo, f"data/{clip_name}.wav", repo_type="dataset")
|
| 315 |
+
audio, sr = sf.read(wav_path)
|
| 316 |
+
|
| 317 |
+
# Resample to 24kHz
|
| 318 |
+
if sr != 24000:
|
| 319 |
+
target_len = int(len(audio) * 24000 / sr)
|
| 320 |
+
audio = np.interp(
|
| 321 |
+
np.linspace(0, len(audio) - 1, target_len),
|
| 322 |
+
np.arange(len(audio)), audio
|
| 323 |
+
).astype(np.float32)
|
| 324 |
+
|
| 325 |
+
# Cap at 10 seconds
|
| 326 |
+
max_samples = 24000 * 10
|
| 327 |
+
if len(audio) > max_samples:
|
| 328 |
+
audio = audio[:max_samples]
|
| 329 |
+
|
| 330 |
+
target_tensor = torch.FloatTensor(audio).to("cuda:0")
|
| 331 |
+
|
| 332 |
+
# Invert
|
| 333 |
+
t0 = time.time()
|
| 334 |
+
codes, loss, cosine = invert_clip(c2w, target_tensor, loss_fn, config, total_upsample)
|
| 335 |
+
elapsed = time.time() - t0
|
| 336 |
+
|
| 337 |
+
if codes is not None:
|
| 338 |
+
torch.save(codes.cpu(), out_path)
|
| 339 |
+
status = "OK" if cosine > 0.7 else "LOW"
|
| 340 |
+
print(f" [{i+1}/{len(my_clips)}] {clip_name} — loss={loss:.3f} cos={cosine:.3f} "
|
| 341 |
+
f"t={elapsed:.0f}s [{status}]")
|
| 342 |
+
results.append({"clip": clip_name, "loss": loss, "cosine": cosine,
|
| 343 |
+
"time": elapsed, "status": status})
|
| 344 |
+
else:
|
| 345 |
+
print(f" [{i+1}/{len(my_clips)}] {clip_name} — too short, skipped")
|
| 346 |
+
results.append({"clip": clip_name, "loss": -1, "cosine": 0, "status": "SKIP"})
|
| 347 |
+
|
| 348 |
+
except Exception as e:
|
| 349 |
+
print(f" [{i+1}/{len(my_clips)}] {clip_name} — ERROR: {e}")
|
| 350 |
+
results.append({"clip": clip_name, "loss": -1, "cosine": 0, "status": f"ERROR: {e}"})
|
| 351 |
+
|
| 352 |
+
# Clear GPU cache between clips
|
| 353 |
+
torch.cuda.empty_cache()
|
| 354 |
+
gc.collect()
|
| 355 |
+
|
| 356 |
+
total_time = time.time() - t_start
|
| 357 |
+
n_ok = sum(1 for r in results if r.get("status") == "OK")
|
| 358 |
+
n_low = sum(1 for r in results if r.get("status") == "LOW")
|
| 359 |
+
avg_cosine = np.mean([r["cosine"] for r in results if r["cosine"] > 0]) if results else 0
|
| 360 |
+
|
| 361 |
+
print(f"\n[{ts()}] === Worker {args.shard_id} Complete ===")
|
| 362 |
+
print(f" Clips: {len(my_clips)} | OK: {n_ok} | Low: {n_low}")
|
| 363 |
+
print(f" Mean cosine: {avg_cosine:.3f}")
|
| 364 |
+
print(f" Total time: {total_time/60:.1f} min ({total_time/len(my_clips):.1f}s/clip)")
|
| 365 |
+
|
| 366 |
+
# Save manifest
|
| 367 |
+
manifest_path = f"{args.output_dir}/manifest_shard{args.shard_id:02d}.json"
|
| 368 |
+
with open(manifest_path, "w") as f:
|
| 369 |
+
json.dump({"shard_id": args.shard_id, "results": results,
|
| 370 |
+
"total_time": total_time}, f, indent=2)
|
| 371 |
+
print(f" Manifest: {manifest_path}")
|
| 372 |
+
|
| 373 |
+
# Upload results to HF
|
| 374 |
+
try:
|
| 375 |
+
from huggingface_hub import HfApi
|
| 376 |
+
api = HfApi()
|
| 377 |
+
api.upload_folder(
|
| 378 |
+
folder_path=args.output_dir,
|
| 379 |
+
repo_id="msrcam/claudia_inverted_codes",
|
| 380 |
+
repo_type="dataset",
|
| 381 |
+
path_in_repo=f"shard_{args.shard_id:02d}",
|
| 382 |
+
)
|
| 383 |
+
print(f" Uploaded to HF: msrcam/claudia_inverted_codes/shard_{args.shard_id:02d}")
|
| 384 |
+
except Exception as e:
|
| 385 |
+
print(f" HF upload failed: {e} — results saved locally")
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
if __name__ == "__main__":
|
| 389 |
+
main()
|