File size: 6,751 Bytes
bda6de8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Probe HuBERT — load fairseq state dict into transformers HubertModel.

Strategy: fairseq HuBERT state dict is structurally identical to transformers HuBERT
in spirit but the post-attention norm is BAKED INTO the attention module's internal
layer_norm. We just need to load what we have; the missing keys are re-initialized
to default values which only matters for the pre-attention norm, but for inference
this is fine.
"""
import os
import sys
import types
import torch

# ---- fairseq shim ----
fake = types.ModuleType("fairseq")
fake_fs_data = types.ModuleType("fairseq.data")
class _Dict:
    def __init__(self, *a, **kw): pass
    def __setstate__(self, s): pass
fake_fs_data_dictionary = types.ModuleType("fairseq.data.dictionary")
fake_fs_data_dictionary.Dictionary = _Dict
sys.modules["fairseq"] = fake
sys.modules["fairseq.data"] = fake_fs_data
sys.modules["fairseq.data.dictionary"] = fake_fs_data_dictionary
fake.data = fake_fs_data
fake_fs_data.dictionary = fake_fs_data_dictionary

from transformers import HubertModel, AutoConfig

CFG = AutoConfig.from_pretrained("facebook/hubert-base-ls960")
m = HubertModel(CFG)
msd = m.state_dict()

pt_path = os.path.expanduser("~/projects/rvc_npu/models/hubert/hubert_base.pt")
ckpt = torch.load(pt_path, map_location="cpu", weights_only=False)
if isinstance(ckpt, dict) and "model" in ckpt and isinstance(ckpt["model"], dict):
    fsd = ckpt["model"]
else:
    fsd = ckpt

# Direct mapping (no positional {i} tricks)
mapping = {
    # conv feature extractor
    "feature_extractor.conv_layers.0.0.weight": "feature_extractor.conv_layers.0.conv.weight",
    "feature_extractor.conv_layers.0.2.weight": "feature_extractor.conv_layers.0.layer_norm.weight",
    "feature_extractor.conv_layers.0.2.bias":   "feature_extractor.conv_layers.0.layer_norm.bias",
    "feature_extractor.conv_layers.1.0.weight": "feature_extractor.conv_layers.1.conv.weight",
    "feature_extractor.conv_layers.1.2.weight": "feature_extractor.conv_layers.1.layer_norm.weight",
    "feature_extractor.conv_layers.1.2.bias":   "feature_extractor.conv_layers.1.layer_norm.bias",
    "feature_extractor.conv_layers.2.0.weight": "feature_extractor.conv_layers.2.conv.weight",
    "feature_extractor.conv_layers.2.2.weight": "feature_extractor.conv_layers.2.layer_norm.weight",
    "feature_extractor.conv_layers.2.2.bias":   "feature_extractor.conv_layers.2.layer_norm.bias",
    "feature_extractor.conv_layers.3.0.weight": "feature_extractor.conv_layers.3.conv.weight",
    "feature_extractor.conv_layers.3.2.weight": "feature_extractor.conv_layers.3.layer_norm.weight",
    "feature_extractor.conv_layers.3.2.bias":   "feature_extractor.conv_layers.3.layer_norm.bias",
    "feature_extractor.conv_layers.4.0.weight": "feature_extractor.conv_layers.4.conv.weight",
    "feature_extractor.conv_layers.4.2.weight": "feature_extractor.conv_layers.4.layer_norm.weight",
    "feature_extractor.conv_layers.4.2.bias":   "feature_extractor.conv_layers.4.layer_norm.bias",
    "feature_extractor.conv_layers.5.0.weight": "feature_extractor.conv_layers.5.conv.weight",
    "feature_extractor.conv_layers.5.2.weight": "feature_extractor.conv_layers.5.layer_norm.weight",
    "feature_extractor.conv_layers.5.2.bias":   "feature_extractor.conv_layers.5.layer_norm.bias",
    "feature_extractor.conv_layers.6.0.weight": "feature_extractor.conv_layers.6.conv.weight",
    "feature_extractor.conv_layers.6.2.weight": "feature_extractor.conv_layers.6.layer_norm.weight",
    "feature_extractor.conv_layers.6.2.bias":   "feature_extractor.conv_layers.6.layer_norm.bias",
    # post feature projection
    "post_extract_proj.weight": "feature_projection.projection.weight",
    "post_extract_proj.bias":   "feature_projection.projection.bias",
    "layer_norm.weight": "feature_projection.layer_norm.weight",
    "layer_norm.bias":   "feature_projection.layer_norm.bias",
    # positional conv (parametrizations: weight_g → original0, weight_v → original1)
    "encoder.pos_conv.0.weight_g": "encoder.pos_conv_embed.conv.parametrizations.weight.original0",
    "encoder.pos_conv.0.weight_v": "encoder.pos_conv_embed.conv.parametrizations.weight.original1",
    "encoder.pos_conv.0.bias":     "encoder.pos_conv_embed.conv.bias",
    # final encoder norm
    "encoder.layer_norm.weight": "encoder.layer_norm.weight",
    "encoder.layer_norm.bias":   "encoder.layer_norm.bias",
}

# Per-layer
for i in range(12):
    mapping.update({
        f"encoder.layers.{i}.self_attn.q_proj.weight":  f"encoder.layers.{i}.attention.q_proj.weight",
        f"encoder.layers.{i}.self_attn.q_proj.bias":    f"encoder.layers.{i}.attention.q_proj.bias",
        f"encoder.layers.{i}.self_attn.k_proj.weight":  f"encoder.layers.{i}.attention.k_proj.weight",
        f"encoder.layers.{i}.self_attn.k_proj.bias":    f"encoder.layers.{i}.attention.k_proj.bias",
        f"encoder.layers.{i}.self_attn.v_proj.weight":  f"encoder.layers.{i}.attention.v_proj.weight",
        f"encoder.layers.{i}.self_attn.v_proj.bias":    f"encoder.layers.{i}.attention.v_proj.bias",
        f"encoder.layers.{i}.self_attn.out_proj.weight":f"encoder.layers.{i}.attention.out_proj.weight",
        f"encoder.layers.{i}.self_attn.out_proj.bias":  f"encoder.layers.{i}.attention.out_proj.bias",
        f"encoder.layers.{i}.fc1.weight": f"encoder.layers.{i}.feed_forward.intermediate_dense.weight",
        f"encoder.layers.{i}.fc1.bias":   f"encoder.layers.{i}.feed_forward.intermediate_dense.bias",
        f"encoder.layers.{i}.fc2.weight": f"encoder.layers.{i}.feed_forward.output_dense.weight",
        f"encoder.layers.{i}.fc2.bias":   f"encoder.layers.{i}.feed_forward.output_dense.bias",
        f"encoder.layers.{i}.final_layer_norm.weight": f"encoder.layers.{i}.final_layer_norm.weight",
        f"encoder.layers.{i}.final_layer_norm.bias":   f"encoder.layers.{i}.final_layer_norm.bias",
    })

new_sd = {}
n_shape_skip = 0
for fk, fv in fsd.items():
    if fk in mapping:
        mk = mapping[fk]
        if mk in msd:
            if msd[mk].shape == fv.shape:
                new_sd[mk] = fv
            else:
                n_shape_skip += 1
                print(f"  [shape skip] {fk} → {mk} fs={tuple(fv.shape)} ms={tuple(msd[mk].shape)}")

print(f"matched tensors: {len(new_sd)}/{len(msd)}; shape-skip={n_shape_skip}")
missing, unexpected = m.load_state_dict(new_sd, strict=False)
print(f"missing: {len(missing)}; unexpected: {len(unexpected)}")
if missing:
    print("  missing examples:", missing[:8])
m.eval()

# Probe time dim
for T_ms in [200, 280, 320, 360, 400, 500, 800, 1000]:
    n = 16 * T_ms
    x = torch.randn(1, n)
    with torch.no_grad():
        y = m(x).last_hidden_state
    print(f"input {T_ms}ms ({n} samples) → output {tuple(y.shape)}")