MCPcopy Create free account
hub / github.com/PABannier/bark.cpp / parse_codec_model_weights

Function parse_codec_model_weights

convert.py:113–199  ·  view source on GitHub ↗

Load encodec model checkpoint.

(checkpoint, outfile, use_f16)

Source from the content-addressed store, hash-verified

111
112
113def parse_codec_model_weights(checkpoint, outfile, use_f16):
114 """Load encodec model checkpoint."""
115 keys = [k for k in checkpoint.keys() if "codec_model" in k]
116
117 for name in keys:
118 if "weight_g" in name:
119 # the tensor has already been parsed with the corresponding "weight_v"
120 # tensor to form the final weights tensor of the convolution, therefore
121 # we skip it
122 continue
123
124 if "inited" in name or "cluster_size" in name or "embed_avg" in name:
125 # "inited", "cluster_size" and "embed_avg" tensors in quantizer are not used
126 # for the forward pass
127 continue
128
129 # Remove prefix from the variable name and the dot
130 clean_name = name.replace("codec_model.", "")
131
132 var_data = checkpoint[name]
133
134 if not "weight_v" in name:
135 # if conv kernel, do not squeeze because 3d tensor
136 var_data = var_data.numpy().squeeze()
137 else:
138 # weight_v has its corresponding magnitude tensor to rescale the weights
139 # of the convolutional layers. We parse both kinds of weights jointly to
140 # build the final weight tensor of the convolution.
141 base_name = name.split(".")[:-1]
142 weight_g_name = ".".join(base_name + ["weight_g"])
143 var_data_g = checkpoint[weight_g_name]
144
145 final_var_data = torch._weight_norm(var_data, var_data_g, dim=0)
146 var_data = final_var_data.numpy()
147
148 name = ".".join(base_name + ["weight"])
149 clean_name = name.replace("codec_model.", "")
150
151 if "encoder" in clean_name or "decoder" in clean_name:
152 if clean_name in DECODER_CONV_TRANSPOSE_LAYERS:
153 pattern = r"decoder.layers.(\d+).conv\.(bias|weight)$"
154 replacement = r"decoder.model.\1.convtr.convtr.\2"
155 clean_name = re.sub(pattern, replacement, clean_name)
156 elif "conv" in clean_name:
157 pattern = r"(encoder|decoder).layers.(\d+)(.*?).conv\.(bias|weight)$"
158 replacement = r"\1.model.\2\3.conv.conv.\4"
159 clean_name = re.sub(pattern, replacement, clean_name)
160 elif "lstm" in clean_name:
161 clean_name = clean_name.replace("layers", "model")
162 elif "quantizer" in clean_name:
163 pattern = r"quantizer.layers.(\d+)\.codebook\.(.+)$"
164 replacement = r"quantizer.vq.layers.\1._codebook.\2"
165 clean_name = re.sub(pattern, replacement, clean_name)
166 else:
167 raise Exception(f"Unrecognized variable name: {clean_name}")
168
169 print(f"Processing variable: {name} with shape: {var_data.shape}")
170

Callers 1

generate_fileFunction · 0.85

Calls 3

subMethod · 0.80
writeMethod · 0.80
closeMethod · 0.80

Tested by

no test coverage detected