Download smkd/seq_scripts.py from SignerX/SignX: direct link, hf CLI and curl.
- Browser
- Download file 15.8 kB
-
https://huggingface.co/datasets/SignerX/SignX/resolve/main/smkd/seq_scripts.py
- Command line
-
hf download hf://datasets/SignerX/SignX/smkd/seq_scripts.py
-
curl -L -o seq_scripts.py https://huggingface.co/datasets/SignerX/SignX/resolve/main/smkd/seq_scripts.py
15.8 kB
| import os | |
| import pdb | |
| import sys | |
| import copy | |
| import torch | |
| import torch.distributed as dist | |
| import h5py | |
| import numpy as np | |
| import torch.nn as nn | |
| from tqdm import tqdm | |
| import torch.nn.functional as F | |
| import contextlib | |
| from pathlib import Path | |
| try: | |
| from torch.distributed.algorithms.join import Join | |
| except ImportError: # pragma: no cover | |
| Join = None | |
| try: | |
| from evaluation.slr_eval.wer_calculation import evaluate | |
| from utils.sample_utils import extract_sample_id | |
| except: | |
| from .evaluation.slr_eval.wer_calculation import evaluate | |
| from .utils.sample_utils import extract_sample_id | |
| def _unwrap_model(model): | |
| return model.module if hasattr(model, "module") else model | |
| def _save_debug_batch_images(data, epoch_idx, batch_idx, recoder): | |
| if os.environ.get("SMKD_DEBUG_SAVE_BATCH", "1") != "1": | |
| return | |
| if epoch_idx != 0 or batch_idx != 0: | |
| return | |
| try: | |
| out_dir = os.environ.get("SMKD_DEBUG_SAVE_DIR", "").strip() | |
| if not out_dir: | |
| if recoder is not None and hasattr(recoder, "log_path"): | |
| out_dir = str(Path(recoder.log_path).parent / "debug_frames") | |
| else: | |
| return | |
| out_path = Path(out_dir) | |
| out_path.mkdir(parents=True, exist_ok=True) | |
| video = data[0] # [B, T, C, H, W] | |
| if not isinstance(video, torch.Tensor) or video.ndim != 5: | |
| return | |
| b, t, c, h, w = video.shape | |
| max_frames = min(int(os.environ.get("SMKD_DEBUG_SAVE_FRAMES", "8")), t) | |
| max_samples = min(int(os.environ.get("SMKD_DEBUG_SAVE_SAMPLES", "1")), b) | |
| for bi in range(max_samples): | |
| for ti in range(max_frames): | |
| frame = video[bi, ti] | |
| # Heuristic un-normalization | |
| fmin = float(frame.min()) | |
| fmax = float(frame.max()) | |
| if fmin < 0 and fmax <= 1.0: | |
| frame = (frame + 1.0) * 127.5 | |
| elif fmax <= 1.0: | |
| frame = frame * 255.0 | |
| frame = frame.clamp(0, 255).byte() | |
| frame = frame.permute(1, 2, 0).cpu().numpy() | |
| out_file = out_path / f"e{epoch_idx:02d}_b{batch_idx:02d}_s{bi}_t{ti}.jpg" | |
| from PIL import Image | |
| Image.fromarray(frame).save(out_file) | |
| if recoder is not None: | |
| recoder.print_log(f"[debug] Saved batch-0 frames to {out_path}") | |
| except Exception as e: | |
| if recoder is not None: | |
| recoder.print_log(f"[debug] Failed to save batch images: {e}") | |
| def _log_debug_batch_stats(data, epoch_idx, batch_idx, recoder): | |
| if os.environ.get("SMKD_DEBUG_STATS", "1") != "1": | |
| return | |
| if epoch_idx != 0 or batch_idx != 0: | |
| return | |
| try: | |
| video = data[0] # [B, T, C, H, W] | |
| if not isinstance(video, torch.Tensor) or video.ndim != 5: | |
| return | |
| mean = float(video.mean().item()) | |
| std = float(video.std().item()) | |
| vmin = float(video.min().item()) | |
| vmax = float(video.max().item()) | |
| msg = f"[debug] Batch-0 video stats (pre-device): mean={mean:.4f} std={std:.4f} min={vmin:.4f} max={vmax:.4f}" | |
| stats_path = os.environ.get("SMKD_DEBUG_STATS_PATH", "").strip() | |
| if not stats_path: | |
| if recoder is not None and hasattr(recoder, "log_path"): | |
| stats_path = str(Path(recoder.log_path).parent / "debug_stats.txt") | |
| if stats_path: | |
| with open(stats_path, "a") as f: | |
| f.write(msg + "\n") | |
| if recoder is not None: | |
| recoder.print_log(msg) | |
| else: | |
| print(msg) | |
| except Exception as e: | |
| if recoder is not None: | |
| recoder.print_log(f"[debug] Failed to compute batch stats: {e}") | |
| def seq_train(loader, model, optimizer, device, epoch_idx, recoder, | |
| is_master=True, rank=0, log_bad_samples=True): | |
| model.train() | |
| base_model = _unwrap_model(model) | |
| loss_value = [] | |
| total_loss_sum = 0.0 | |
| total_loss_count = 0 | |
| bad_sample_ids = [] if log_bad_samples else None | |
| clr = [group['lr'] for group in optimizer.optimizer.param_groups] | |
| join_context = contextlib.nullcontext() | |
| if Join is not None and dist.is_available() and dist.is_initialized(): | |
| join_context = Join([model]) | |
| with join_context: | |
| for batch_idx, data in enumerate(tqdm(loader, disable=not is_master)): | |
| if is_master: | |
| _save_debug_batch_images(data, epoch_idx, batch_idx, recoder) | |
| _log_debug_batch_stats(data, epoch_idx, batch_idx, recoder) | |
| vid = device.data_to_device(data[0]) | |
| vid_lgt = device.data_to_device(data[1]) | |
| label = device.data_to_device(data[2]) | |
| label_lgt = device.data_to_device(data[3]) | |
| ret_dict = model(vid, vid_lgt, label=label, label_lgt=label_lgt) | |
| loss = base_model.criterion_calculation(ret_dict, label, label_lgt) | |
| loss_item = loss.detach().item() | |
| finite = np.isfinite(loss_item) | |
| if not finite: | |
| batch_ids = [] | |
| if log_bad_samples: | |
| for info in data[-1]: | |
| sid = extract_sample_id(info) | |
| if sid: | |
| batch_ids.append(sid) | |
| if batch_ids and bad_sample_ids is not None: | |
| bad_sample_ids.extend(batch_ids) | |
| msg = f"[rank {rank}] Non-finite loss at epoch {epoch_idx}, batch {batch_idx}, sample {batch_ids or data[-1]}" | |
| if recoder is not None and is_master: | |
| recoder.print_log(msg) | |
| else: | |
| print(msg) | |
| loss = torch.nan_to_num(loss, nan=0.0, posinf=0.0, neginf=0.0) | |
| else: | |
| total_loss_sum += float(loss_item) | |
| total_loss_count += 1 | |
| optimizer.zero_grad() | |
| loss.backward() | |
| # nn.utils.clip_grad_norm_(model.rnn.parameters(), 5) | |
| optimizer.step() | |
| loss_value.append(loss_item if finite else np.nan) | |
| if batch_idx % recoder.log_interval == 0: | |
| # Check if pose assistance is enabled and get current weight | |
| log_msg = '\tEpoch: {}, Batch({}/{}) done. Loss: {:.8f} lr:{:.6f}'.format( | |
| epoch_idx, batch_idx, len(loader), | |
| loss_item if finite else 0.0, clr[0]) | |
| # Add pose assist weight if enabled | |
| if hasattr(base_model, 'multimodal_pose_assist') and base_model.multimodal_pose_assist: | |
| try: | |
| current_weight = base_model.get_pose_assist_weight() | |
| if isinstance(current_weight, torch.Tensor): | |
| current_weight = current_weight.item() | |
| # 计算当前权重占初始权重的百分比 | |
| weight_percentage = (current_weight / base_model.pose_assist_weight_init * 100) if base_model.pose_assist_weight_init > 0 else 0 | |
| log_msg += ' pose_w:{:.6f}({:.1f}%)'.format(current_weight, weight_percentage) | |
| except: | |
| pass # 如果获取权重失败,不影响正常日志 | |
| recoder.print_log(log_msg) | |
| optimizer.scheduler.step() | |
| valid_losses = np.array([lv for lv in loss_value if np.isfinite(lv)], dtype=np.float64) | |
| if valid_losses.size > 0: | |
| mean_loss = float(valid_losses.mean()) | |
| else: | |
| mean_loss = float('nan') | |
| recoder.print_log('\tMean training loss: {:.10f}.'.format(mean_loss)) | |
| # Print pose assist weight summary at epoch end | |
| if hasattr(base_model, 'multimodal_pose_assist') and base_model.multimodal_pose_assist: | |
| try: | |
| current_weight = base_model.get_pose_assist_weight() | |
| if isinstance(current_weight, torch.Tensor): | |
| current_weight = current_weight.item() | |
| weight_percentage = (current_weight / base_model.pose_assist_weight_init * 100) if base_model.pose_assist_weight_init > 0 else 0 | |
| if base_model.pose_assist_learnable: | |
| # 可学习权重,显示参数值和sigmoid后的alpha | |
| param_value = base_model.pose_assist_weight_param.item() | |
| alpha = torch.sigmoid(torch.tensor(param_value)).item() | |
| recoder.print_log( | |
| '\tPose Assist Weight: {:.6f} ({:.1f}% of max={:.6f}) [learnable_param={:.4f}, sigmoid={:.4f}]'.format( | |
| current_weight, weight_percentage, base_model.pose_assist_weight_init, param_value, alpha)) | |
| else: | |
| # 固定权重 | |
| recoder.print_log( | |
| '\tPose Assist Weight: {:.6f} (FIXED)'.format(current_weight)) | |
| except: | |
| pass | |
| return total_loss_sum, total_loss_count, bad_sample_ids if log_bad_samples else None | |
| def seq_eval(cfg, loader, model, device, mode, epoch, work_dir, recoder, | |
| evaluate_tool="python", is_master=True): | |
| model.eval() | |
| eval_model = _unwrap_model(model) | |
| total_sent = [] | |
| total_info = [] | |
| total_conv_sent = [] | |
| stat = {i: [0, 0] for i in range(len(loader.dataset.dict))} | |
| for batch_idx, data in enumerate(tqdm(loader, disable=not is_master)): | |
| recoder.record_timer("device") | |
| vid = device.data_to_device(data[0]) | |
| vid_lgt = device.data_to_device(data[1]) | |
| label = device.data_to_device(data[2]) | |
| label_lgt = device.data_to_device(data[3]) | |
| with torch.no_grad(): | |
| ret_dict = eval_model(vid, vid_lgt, label=label, label_lgt=label_lgt) | |
| if is_master and getattr(cfg, "debug_seq_topk", 0) and batch_idx == 0: | |
| try: | |
| k = int(getattr(cfg, "debug_seq_topk", 0)) | |
| if k > 0: | |
| seq_logits = ret_dict.get("sequence_logits") | |
| if seq_logits is not None and seq_logits.numel() > 0: | |
| probs = seq_logits.softmax(-1).detach() | |
| probs0 = probs[:, 0, :] if probs.dim() == 3 else probs[0] | |
| mean_probs = probs0.mean(dim=0).cpu() | |
| top_vals, top_idx = torch.topk(mean_probs, k) | |
| i2g = {v[0]: g for g, v in loader.dataset.dict.items()} | |
| items = [] | |
| for score, idx in zip(top_vals.tolist(), top_idx.tolist()): | |
| token = i2g.get(int(idx), f"<{int(idx)}>") | |
| items.append(f"{token}:{score:.4f}") | |
| blank_prob = float(mean_probs[0].item()) if mean_probs.numel() > 0 else 0.0 | |
| recoder.print_log( | |
| f"[DEBUG] SeqHead top-{k} avg probs: {', '.join(items)} " | |
| f"(blank={blank_prob:.4f})" | |
| ) | |
| except Exception as e: | |
| recoder.print_log(f"[DEBUG] SeqHead top-k failed: {e}") | |
| if is_master and getattr(cfg, "debug_conv_topk", 0) and batch_idx == 0: | |
| try: | |
| k = int(getattr(cfg, "debug_conv_topk", 0)) | |
| if k > 0: | |
| conv_logits = ret_dict.get("conv_logits") | |
| if conv_logits is not None and conv_logits.numel() > 0: | |
| probs = conv_logits.softmax(-1).detach() | |
| probs0 = probs[:, 0, :] if probs.dim() == 3 else probs[0] | |
| mean_probs = probs0.mean(dim=0).cpu() | |
| top_vals, top_idx = torch.topk(mean_probs, k) | |
| i2g = {v[0]: g for g, v in loader.dataset.dict.items()} | |
| items = [] | |
| for score, idx in zip(top_vals.tolist(), top_idx.tolist()): | |
| token = i2g.get(int(idx), f"<{int(idx)}>") | |
| items.append(f"{token}:{score:.4f}") | |
| blank_prob = float(mean_probs[0].item()) if mean_probs.numel() > 0 else 0.0 | |
| recoder.print_log( | |
| f"[DEBUG] ConvHead top-{k} avg probs: {', '.join(items)} " | |
| f"(blank={blank_prob:.4f})" | |
| ) | |
| except Exception as e: | |
| recoder.print_log(f"[DEBUG] ConvHead top-k failed: {e}") | |
| total_info += [file_name[2] for file_name in data[-1]] | |
| total_sent += ret_dict['recognized_sents'] | |
| total_conv_sent += ret_dict['conv_sents'] | |
| try: | |
| python_eval = True if evaluate_tool == "python" else False | |
| write2file(work_dir + "output-hypothesis-{}.ctm".format(mode), total_info, total_sent) | |
| write2file(work_dir + "output-hypothesis-{}-conv.ctm".format(mode), total_info, | |
| total_conv_sent) | |
| conv_ret = evaluate( | |
| prefix=work_dir, mode=mode, output_file="output-hypothesis-{}-conv.ctm".format(mode), | |
| evaluate_dir=cfg.dataset_info['evaluation_dir'], | |
| dataset_dir=cfg.dataset_info['dataset_root'], | |
| evaluate_prefix=cfg.dataset_info['evaluation_prefix'], | |
| output_dir="epoch_{}_result/".format(epoch), | |
| python_evaluate=python_eval, | |
| ) | |
| lstm_ret = evaluate( | |
| prefix=work_dir, mode=mode, output_file="output-hypothesis-{}.ctm".format(mode), | |
| evaluate_dir=cfg.dataset_info['evaluation_dir'], | |
| dataset_dir=cfg.dataset_info['dataset_root'], | |
| evaluate_prefix=cfg.dataset_info['evaluation_prefix'], | |
| output_dir="epoch_{}_result/".format(epoch), | |
| python_evaluate=python_eval, | |
| triplet=True, | |
| ) | |
| except: | |
| print("Unexpected error:", sys.exc_info()[0]) | |
| lstm_ret = 100.0 | |
| finally: | |
| pass | |
| use_conv = getattr(cfg, "eval_use_conv", False) | |
| chosen = conv_ret if use_conv else lstm_ret | |
| suffix = " (conv)" if use_conv else "" | |
| recoder.print_log(f"Epoch {epoch}, {mode} {chosen: 2.2f}%{suffix}", f"{work_dir}/{mode}.txt") | |
| return chosen | |
| def seq_feature_generation(loader, model, device, mode, recoder, is_master=True): | |
| model.eval() | |
| feature_model = _unwrap_model(model) | |
| tgt_path = os.path.abspath(f"./features/{mode}") | |
| if not os.path.exists("./features/"): | |
| os.makedirs("./features/") | |
| features = {} | |
| for batch_idx, data in tqdm(enumerate(loader), disable=not is_master): | |
| recoder.record_timer("device") | |
| vid = device.data_to_device(data[0]) | |
| vid_lgt = device.data_to_device(data[1]) | |
| with torch.no_grad(): | |
| ret_dict = feature_model(vid, vid_lgt) | |
| feat_len = ret_dict['feat_len'].cpu().detach().numpy().astype(np.int32) | |
| visual_features = ret_dict['visual_features'].permute(1, 0, 2) | |
| for sample_idx in range(len(vid)): | |
| visual_feature = visual_features[sample_idx][:feat_len[sample_idx]].cpu().detach().numpy().astype(np.float32) | |
| features[data[-1][sample_idx][1]] = visual_feature | |
| hf = h5py.File(tgt_path + ".h5", 'w') | |
| fkeys = sorted(list(features.keys())) | |
| for i, dkey in enumerate(fkeys): | |
| feature = features[dkey] | |
| hf.create_dataset("%s" % i, data=feature) | |
| hf.close() | |
| def write2file(path, info, output): | |
| with open(path, "w") as filereader: | |
| for sample_idx, sample in enumerate(output): | |
| for word_idx, word in enumerate(sample): | |
| filereader.writelines( | |
| "{} 1 {:.2f} {:.2f} {}\n".format(info[sample_idx], | |
| word_idx * 1.0 / 100, | |
| (word_idx + 1) * 1.0 / 100, | |
| word[0])) | |