Upload folder using huggingface_hub
Browse filesFiles changed (5)
- LICENSEAdded+107
- README.mdAdded+47
- emotion2vec_plus_large.onnxAdded+3
- export_emotion2vec.pyAdded+205
- export_report.jsonAdded+55
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107FunASR Model Open Source License Agreement
Version: 1.1
Copyright (C) [2023-2028] [Alibaba Group]. All rights reserved.
Thank you for choosing the FunASR open-source model. The FunASR open-source model includes a range of free and open industrial models for you to use, modify, share, and learn from.
To ensure better community collaboration, we have established the following agreement, and we hope you will read and comply with its terms.Definitions
In this agreement, [FunASR Software] refers to FunASR open-source model weights and their derivatives, including finetuned models; [You] refers to individuals or organizations using, modifying, sharing, and learning from [FunASR Software].
2 License and Restrictions
2.1 License
You are free to use, copy, modify, and share [FunASR Software] under the terms of this agreement.
2.2 Restrictions
When using, copying, modifying, and sharing [FunASR Software], you must attribute the source and author information and retain relevant model names in [FunASR Software].
3 Responsibility and Risk
[FunASR Software] is provided for reference and learning purposes only, and Alibaba Group assumes no responsibility for any direct or indirect losses resulting from your use or modification of [FunASR Software]. You should assume all risks associated with using and modifying [FunASR Software].
4 Community Conduct Guidelines
4.1 Encouraged Behavior
The community welcomes developers and users to engage in discussions about [FunASR Software]. Participants are encouraged to interact in a friendly, polite, and respectful manner to foster constructive discussion and collaboration.
4.2 Prohibited Behavior
Individual or organizational users shall not engage in unjustified denigration, malicious smearing, or baseless insults against [FunASR Software]. Such behavior is considered a violation of the spirit of community cooperation. If a user is found to be engaging in the prohibited behavior mentioned above, it will be considered an automatic forfeiture of all licenses under this agreement.
5 Termination
If you violate any terms of this agreement, your license will automatically terminate, and you must cease using, copying, modifying, and sharing [FunASR Software].
6 Revisions
This agreement may be updated and revised occasionally. The revised agreement will be published in the official repository of [FunASR Software] and will take effect automatically. Continuing to use, copy, modify, and share [FunASR Software] indicates your acceptance of the revised agreement.
7 Miscellaneous
This agreement is governed by the laws of [Country/Region]. If any provision is deemed illegal, invalid, or unenforceable, that provision shall be considered severed from this agreement, and the remaining provisions shall continue to be valid and binding.
If you have any questions or comments regarding this agreement, please contact us.
Copyright © [2023-2028] [Alibaba Group]. All rights reserved.
FunASR 模型开源协议
版本号:1.1
版权所有 (C) [2023-2028] [阿里巴巴集团]。保留所有权利。
感谢您选择 FunASR 开源模型。FunASR 开源模型包含一系列免费且开源的工业模型,让大家可以使用、修改、分享和学习该模型。
为了保证更好的社区合作,我们制定了以下协议,希望您仔细阅读并遵守本协议。
1 定义
本协议中,[FunASR 软件]指 FunASR 开源模型权重及其衍生品,包括 Finetune 后的模型;[您]指使用、修改、分享和学习[FunASR 软件]的个人或组织。
2 许可和限制
2.1 许可
您可以在遵守本协议的前提下,自由地使用、复制、修改和分享[FunASR 软件]。
2.2 限制
您在使用、复制、修改和分享[FunASR 软件]时,必须注明出处以及作者信息,并保留[FunASR 软件]中相关模型名称。
3 责任和风险承担
[FunASR 软件]仅作为参考和学习使用,不对您使用或修改[FunASR 软件]造成的任何直接或间接损失承担任何责任。您对[FunASR 软件]的使用和修改应该自行承担风险。
4 社区行为准则
4.1 欢迎交流
社区欢迎开发者与用户对[FunASR 软件]进行交流讨论。交流中请注意保持友好、礼貌和文明,以促进建设性的讨论和合作。
4.2 禁止行为
个人或组织用户不得对[FunASR 软件]进行无端诋毁、恶意抹黑或凭空谩骂。此类行为被视为违反社区合作精神。如被认定从事上述禁止行为,将视为自动放弃本协议下的所有许可。
5 终止
如果您违反本协议的任何条款,您的许可将自动终止,您必须停止使用、复制、修改和分享[FunASR 软件]。
6 修订
本协议可能会不时更新和修订。修订后的协议将在[FunASR 软件]官方仓库发布,并自动生效。如果您继续使用、复制、修改和分享[FunASR 软件],即表示您同意修订后的协议。
7 其他规定
本协议受到[国家/地区] 的法律管辖。如果任何条款被裁定为不合法、无效或无法执行,则该条款应被视为从本协议中删除,而其余条款应继续有效并具有约束力。
如果您对本协议有任何问题或意见,请联系我们。
版权所有© [2023-2028] [阿里巴巴集团]。保留所有权利。1234567891011121314151617181920212223242526272829303132333435363738394041424344454647---license: otherlicense_name: funasr-model-licenselicense_link: LICENSEbase_model: emotion2vec/emotion2vec_plus_largepipeline_tag: audio-classificationtags: - onnx - speech-emotion-recognition - emotion2vec---
# emotion2vec+ large (ONNX)
Export em ONNX do [emotion2vec/emotion2vec_plus_large](https://huggingface.co/emotion2vec/emotion2vec_plus_large)(revisão `6c303ba987b86b93193de93e34bb2b077a6bedc4`), com os mesmos pesos, para rodar no ONNX Runtime sem PyTorch.Não é um modelo novo: o crédito é dos autores do emotion2vec (Ziyang Ma et al.) e do FunASR (Alibaba Group).
| Arquivo | Conteúdo ||---|---|| `emotion2vec_plus_large.onnx` | Entrada `audio`: (1, N) float32, mono, 16 kHz, entre -1 e 1. Saída `scores`: (1, 9), probabilidades || `export_emotion2vec.py` | Script que gerou o arquivo e conferiu a saída contra o código do FunASR 1.4.16 || `export_report.json` | Diferença máxima entre o ONNX e o PyTorch em 6 durações (0,5 s a 30 s) |
O grafo já faz o que o `Emotion2vec.inference` do FunASR faz no modo `granularity="utterance"`: normaliza o áudio(média e variância do áudio inteiro), extrai os frames, tira a média, aplica a camada `proj` e o softmax.Os rótulos ficam nos metadados do ONNX (`labels`), nesta ordem: `angry`, `disgusted`, `fearful`, `happy`,`neutral`, `other`, `sad`, `surprised`, `unknown`.
A única mudança no código do modelo durante o export foi o cálculo do viés ALiBi, que o FunASR guarda num cachede tamanho fixo. O export usa uma versão que calcula o viés a partir do tamanho da entrada, com o mesmo resultado(diferença máxima de 2,9e-6 nas probabilidades).
## Licença
FunASR Model Open Source License, herdada do modelo original (ver `LICENSE`).
## Citação
```bibtex@article{ma2023emotion2vec, title={emotion2vec: Self-Supervised Pre-Training for Speech Emotion Representation}, author={Ma, Ziyang and Zheng, Zhisheng and Ye, Jiaxin and Li, Jinchao and Gao, Zhifu and Zhang, Shiliang and Chen, Xie}, journal={arXiv preprint arXiv:2312.15185}, year={2023}}```123version https://git-lfs.github.com/spec/v1oid sha256:fb3857310f20d298ee3f10dcebf01bdbb69d4e1722f8f0aa7cea20d31324417fsize 648984830123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205"""Exporta o emotion2vec+ large oficial para ONNX e confere a saída contra o código do FunASR.
Roda uma vez, fora do Pod, num venv descartável com torch (o gateway nunca importa torch). O ONNXgerado vai para um repo do Hugging Face e fica fixado por commit e SHA-256 em gateway/core/pins.py.
O grafo recebe o áudio cru (1, N) float32 a 16 kHz e devolve as probabilidades (1, 9), com a contado Emotion2vec.inference do FunASR: layer_norm do áudio inteiro, média dos frames, proj e softmax.
python -m venv venv-export venv-export/bin/pip install torch==2.14.1 --index-url https://download.pytorch.org/whl/cpu venv-export/bin/pip install --no-deps funasr==1.4.16 venv-export/bin/pip install numpy onnx onnxruntime huggingface_hub soundfile omegaconf pyyaml \ kaldiio librosa setuptools venv-export/bin/python -I scripts/export_emotion2vec.py <pasta de saída>"""
import jsonimport mathimport osimport sys
import numpy as npimport onnximport onnxruntime as ortimport soundfileimport torchimport yamlfrom funasr.models.emotion2vec import audio as e2v_audiofrom funasr.models.emotion2vec import base as e2v_basefrom funasr.models.emotion2vec.model import Emotion2vecfrom huggingface_hub import snapshot_download
UPSTREAM_REPO = "emotion2vec/emotion2vec_plus_large"UPSTREAM_REVISION = "6c303ba987b86b93193de93e34bb2b077a6bedc4"ONNX_FILE = "emotion2vec_plus_large.onnx"SAMPLING_RATE = 16000# Durações diferentes da usada no trace: confere que nenhum tamanho ficou fixo no grafo.CHECK_SECONDS = (0.5, 1.7, 7.3, 20.0, 30.0)# Teto da diferença entre as probabilidades do ONNX e as do PyTorch.MAX_ABS_DIFF = 1e-4
def dynamic_alibi_bias(alibi_biases, batch_size, time_steps, heads, dtype, device, dims=1, distance="manhattan"): """ALiBi 1D calculado do tamanho da entrada, sem o cache em dict do FunASR (que o tracer congelaria).
Args: alibi_biases (dict): Cache do FunASR, ignorado. batch_size (int): Tamanho do lote. time_steps (int): Frames da sequência. heads (int): Cabeças de atenção (potência de 2). dtype (torch.dtype): Tipo do viés. device (torch.device): Dispositivo do viés. dims (int, opcional): Só 1 (áudio). distance (str, opcional): Ignorado em 1D.
Returns: torch.Tensor: Viés (batch_size, heads, time_steps, time_steps). """ log2 = math.log2(heads) assert dims == 1 and log2.is_integer(), (dims, heads) start = 2 ** (-(2 ** -(log2 - 3))) slopes = torch.tensor([start * start ** i for i in range(heads)], dtype=dtype, device=device) pos = torch.arange(time_steps, device=device) pos_bias = -(pos.unsqueeze(0) - pos.unsqueeze(1)).abs().to(dtype) bias = slopes.view(heads, 1, 1) * pos_bias.unsqueeze(0) return bias.unsqueeze(0).expand(batch_size, -1, -1, -1)
class Classifier(torch.nn.Module): """Emotion2vec com a cabeça de classificação, igual ao caminho granularity="utterance" do FunASR."""
def __init__(self, model: Emotion2vec): """Guarda o modelo carregado.
Args: model (Emotion2vec): Modelo com proj (vocab_size=9). """ super().__init__() self.model = model
def forward(self, audio: torch.Tensor) -> torch.Tensor: """Calcula as probabilidades das classes.
Args: audio (torch.Tensor): (1, N) float32 a 16 kHz.
Returns: torch.Tensor: (1, 9) probabilidades. """ # F.layer_norm(source, source.shape) do FunASR: média e variância do áudio inteiro, eps 1e-5. mean = audio.mean(dim=1, keepdim=True) var = audio.var(dim=1, keepdim=True, unbiased=False) x = (audio - mean) / torch.sqrt(var + 1e-5) feats = self.model.extract_features(x, padding_mask=None)["x"] return torch.softmax(self.model.proj(feats.mean(dim=1)), dim=-1)
def build(upstream: str, alibi) -> tuple: """Monta o Emotion2vec com o config e os pesos oficiais.
Args: upstream (str): Pasta com config.yaml, tokens.txt e model.pt. alibi (Callable): get_alibi_bias que o AudioEncoder liga na construção.
Returns: tuple: (Classifier em eval, rótulos em inglês). """ e2v_audio.get_alibi_bias = alibi with open(os.path.join(upstream, "config.yaml"), encoding="utf-8") as f: cfg = yaml.safe_load(f) # tokens.txt traz "生气/angry"...; fica só o nome em inglês, e o "<unk>" vira "unknown". with open(os.path.join(upstream, "tokens.txt"), encoding="utf-8") as f: labels = [line.strip().split("/")[-1].replace("<unk>", "unknown") for line in f if line.strip()] model = Emotion2vec(model_conf=cfg["model_conf"], vocab_size=len(labels)) # weights_only: o pickle do checkpoint não executa código. state = torch.load(os.path.join(upstream, "model.pt"), map_location="cpu", weights_only=True)["model"] state = {k.removeprefix("d2v_model."): v for k, v in state.items()} result = model.load_state_dict(state, strict=False) # O decoder só serve ao pré-treino; qualquer outra sobra seria um checkpoint diferente. assert not result.unexpected_keys, result.unexpected_keys assert all(".decoder." in k for k in result.missing_keys), result.missing_keys return Classifier(model.eval()), labels
def read_wav(path: str) -> np.ndarray: """Lê um WAV mono a 16 kHz.
Args: path (str): Caminho do arquivo.
Returns: np.ndarray: Amostras float32. """ data, sr = soundfile.read(path, dtype="float32") assert sr == SAMPLING_RATE and data.ndim == 1, (sr, data.shape) return data
def check(reference: Classifier, path: str, example: np.ndarray, labels: list) -> dict: """Compara o ONNX com o PyTorch no exemplo oficial e em recortes de outras durações.
Args: reference (Classifier): Modelo com o ALiBi original do FunASR. path (str): ONNX exportado. example (np.ndarray): example/test.wav do repo oficial. labels (list): Rótulos na ordem da saída.
Returns: dict: Relatório com a diferença máxima de cada caso. """ session = ort.InferenceSession(path, providers=["CPUExecutionProvider"]) rng = np.random.default_rng(0) cases = {"example": example} for seconds in CHECK_SECONDS: cases[f"{seconds}s"] = (np.resize(example, int(seconds * SAMPLING_RATE)) * rng.uniform(0.3, 1.0)) report = {"cases": {}} for name, audio in cases.items(): audio = audio.astype(np.float32)[None, :] with torch.no_grad(): ref = reference(torch.from_numpy(audio)).numpy()[0] got = session.run(None, {"audio": audio})[0][0] diff = float(np.abs(ref - got).max()) report["cases"][name] = {"samples": audio.shape[1], "max_abs_diff": diff, "torch_top": labels[int(ref.argmax())], "onnx_top": labels[int(got.argmax())]} print(f"{name}: {audio.shape[1]} samples, max_abs_diff={diff:.2e}, top={labels[int(got.argmax())]}") report["max_abs_diff"] = max(case["max_abs_diff"] for case in report["cases"].values()) return report
def main(): """Baixa o upstream fixado, exporta, grava rótulos e origem no ONNX e confere a saída.""" out_dir = sys.argv[1] os.makedirs(out_dir, exist_ok=True) upstream = snapshot_download(UPSTREAM_REPO, revision=UPSTREAM_REVISION, allow_patterns=["model.pt", "config.yaml", "tokens.txt", "example/test.wav"]) # Referência numa instância própria, com o ALiBi original: o export altera o estado do # modelo exportado, e a comparação também cobre a troca do ALiBi. reference, labels = build(upstream, e2v_base.get_alibi_bias) exported, _ = build(upstream, dynamic_alibi_bias) example = read_wav(os.path.join(upstream, "example", "test.wav")) path = os.path.join(out_dir, ONNX_FILE) with torch.no_grad(): torch.onnx.export( exported, (torch.from_numpy(example).unsqueeze(0),), path, dynamo=False, opset_version=17, input_names=["audio"], output_names=["scores"], dynamic_axes={"audio": {1: "samples"}}, )
# Rótulos e origem dentro do próprio ONNX: o gateway lê daí, sem arquivo à parte. model = onnx.load(path) metadata = {"labels": json.dumps(labels), "sampling_rate": str(SAMPLING_RATE), "source": f"{UPSTREAM_REPO}@{UPSTREAM_REVISION}", "license": "FunASR Model Open Source License"} for key, value in metadata.items(): model.metadata_props.add(key=key, value=value) onnx.save(model, path)
report = check(reference, path, example, labels) report.update(labels=labels, **{k: v for k, v in metadata.items() if k != "labels"}) with open(os.path.join(out_dir, "export_report.json"), "w", encoding="utf-8") as f: json.dump(report, f, indent=1) assert report["max_abs_diff"] < MAX_ABS_DIFF, report["max_abs_diff"] print(f"{path} ok (max_abs_diff={report['max_abs_diff']:.2e})")
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455{
"cases": {
"example": {
"samples": 65666,
"max_abs_diff": 1.1562972801471005e-13,
"torch_top": "angry",
"onnx_top": "angry"
},
"0.5s": {
"samples": 8000,
"max_abs_diff": 2.8759241104125977e-06,
"torch_top": "disgusted",
"onnx_top": "disgusted"
},
"1.7s": {
"samples": 27200,
"max_abs_diff": 1.1920928955078125e-07,
"torch_top": "angry",
"onnx_top": "angry"
},
"7.3s": {
"samples": 116800,
"max_abs_diff": 1.688649220454863e-13,
"torch_top": "angry",
"onnx_top": "angry"
},
"20.0s": {
"samples": 320000,
"max_abs_diff": 3.61524143954739e-10,
"torch_top": "angry",
"onnx_top": "angry"
},
"30.0s": {
"samples": 480000,
"max_abs_diff": 3.888999344781041e-09,
"torch_top": "angry",
"onnx_top": "angry"
}
},
"max_abs_diff": 2.8759241104125977e-06,
"labels": [
"angry",
"disgusted",
"fearful",
"happy",
"neutral",
"other",
"sad",
"surprised",
"unknown"
],
"sampling_rate": "16000",
"source": "emotion2vec/emotion2vec_plus_large@6c303ba987b86b93193de93e34bb2b077a6bedc4",
"license": "FunASR Model Open Source License"
}LICENSEAdded+107
README.mdAdded+47
emotion2vec_plus_large.onnxAdded+3
export_emotion2vec.pyAdded+205
export_report.jsonAdded+55