Initial upload: XEUS weights converted to SafeTensors with pure-PyTorch modeling and CC-BY-NC-SA 4.0 license
Browse files- LICENSE +49 -0
- README.md +113 -0
- config.json +14 -0
- model.safetensors +3 -0
- modeling_xeus.py +303 -0
LICENSE
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)
|
| 2 |
+
|
| 3 |
+
By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
|
| 4 |
+
|
| 5 |
+
Section 1 -- Definitions.
|
| 6 |
+
|
| 7 |
+
a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor.
|
| 8 |
+
b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
|
| 9 |
+
c. CC-BY-NC-SA Compatible License means a license that is listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License.
|
| 10 |
+
d. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized.
|
| 11 |
+
e. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
|
| 12 |
+
f. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
|
| 13 |
+
g. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
|
| 14 |
+
h. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
|
| 15 |
+
i. Licensor means the individual(s) or entity(ies) granting rights under this Public License.
|
| 16 |
+
j. NonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation.
|
| 17 |
+
k. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation.
|
| 18 |
+
l. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
|
| 19 |
+
m. You means the individual or entity exercising the Licensed Rights under this Public License.
|
| 20 |
+
|
| 21 |
+
Section 2 -- Scope.
|
| 22 |
+
|
| 23 |
+
a. License grant.
|
| 24 |
+
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
|
| 25 |
+
A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
|
| 26 |
+
B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only.
|
| 27 |
+
2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
|
| 28 |
+
3. Term. The term of this Public License is specified in Section 6(a).
|
| 29 |
+
4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so.
|
| 30 |
+
|
| 31 |
+
Section 3 -- License Conditions.
|
| 32 |
+
|
| 33 |
+
Your exercise of the Licensed Rights is expressly made subject to the following conditions.
|
| 34 |
+
|
| 35 |
+
a. Attribution.
|
| 36 |
+
If You Share the Licensed Material, You must:
|
| 37 |
+
1. retain the following if it is supplied by the Licensor with the Licensed Material:
|
| 38 |
+
A. identification of the creator(s) of the Licensed Material and any others designated to receive attribution;
|
| 39 |
+
B. a copyright notice;
|
| 40 |
+
C. a notice that refers to this Public License;
|
| 41 |
+
D. a notice that refers to the disclaimer of warranties;
|
| 42 |
+
E. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
|
| 43 |
+
2. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
|
| 44 |
+
3. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
|
| 45 |
+
|
| 46 |
+
b. ShareAlike.
|
| 47 |
+
In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the Adapter's License You apply must be a CC-BY-NC-SA Compatible License with the same license version.
|
| 48 |
+
|
| 49 |
+
For the full legal code, visit: https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode
|
README.md
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: cc-by-nc-sa-4.0
|
| 3 |
+
library_name: generic
|
| 4 |
+
tags:
|
| 5 |
+
- audio
|
| 6 |
+
- speech
|
| 7 |
+
- multilingual
|
| 8 |
+
- automatic-speech-recognition
|
| 9 |
+
- safetensors
|
| 10 |
+
- e-branchformer
|
| 11 |
+
- acoustic-encoder
|
| 12 |
+
datasets:
|
| 13 |
+
- espnet/yodas
|
| 14 |
+
- facebook/voxpopuli
|
| 15 |
+
- facebook/multilingual_librispeech
|
| 16 |
+
- google/fleurs
|
| 17 |
+
- openslr/librispeech_asr
|
| 18 |
+
- speechcolab/gigaspeech
|
| 19 |
+
- cheulyop/ksponspeech
|
| 20 |
+
- espnet/mms_ulab_v2
|
| 21 |
+
---
|
| 22 |
+
|
| 23 |
+
# XEUS: Cross-lingual E-Branchformer Universal Speech Representation (SafeTensors)
|
| 24 |
+
|
| 25 |
+
This repository provides the **SafeTensors** conversion and standalone pure-PyTorch implementation of **XEUS**, originally developed by Carnegie Mellon University's [WAVLab](https://www.wavlab.org/).
|
| 26 |
+
|
| 27 |
+
- **Original Hub Repository:** [espnet/xeus](https://huggingface.co/espnet/xeus)
|
| 28 |
+
- **Paper:** [XEUS: A Cross-lingual Encoder for Universal Speech](https://wanchichen.github.io/pdf/xeus.pdf)
|
| 29 |
+
- **Architecture:** E-Branchformer (19 layers, 577M parameters)
|
| 30 |
+
- **Pretraining scale:** 1,000,000+ hours across 4,000+ languages
|
| 31 |
+
- **Input:** 16 kHz raw audio waveform `(batch_size, time_samples)`
|
| 32 |
+
- **Output:** Frame representations `(batch_size, time_frames, 1024)` at 50 Hz frame rate (stride 320, 20ms per frame)
|
| 33 |
+
- **Weight format:** `model.safetensors` (fast, zero arbitrary code execution, memory-mapped)
|
| 34 |
+
|
| 35 |
+
---
|
| 36 |
+
|
| 37 |
+
## Architecture Specifications
|
| 38 |
+
|
| 39 |
+
| Parameter | Value |
|
| 40 |
+
| :--- | :--- |
|
| 41 |
+
| Pretrained Objective | HuBERT-style masked prediction + acoustic noise & reverberation augmentation |
|
| 42 |
+
| Input Format | Raw mono waveform at 16,000 Hz |
|
| 43 |
+
| Frontend | 7-layer Conv1d extractor (strides: 5, 2, 2, 2, 2, 2, 2; total stride: 320) |
|
| 44 |
+
| Feature Dimension ($d_{model}$) | 1024 |
|
| 45 |
+
| Intermediate FFN Dimension | 4096 |
|
| 46 |
+
| Number of E-Branchformer Layers | 19 |
|
| 47 |
+
| Attention Heads | 8 |
|
| 48 |
+
| CGMLP / CSGU Kernel Size | 31 (depthwise) |
|
| 49 |
+
| Output Frame Rate | 50.0 Hz |
|
| 50 |
+
|
| 51 |
+
---
|
| 52 |
+
|
| 53 |
+
## Standalone Quickstart (No ESPnet installation required)
|
| 54 |
+
|
| 55 |
+
This repository includes a standalone [`modeling_xeus.py`](modeling_xeus.py) implementation that runs on pure PyTorch without requiring ESPnet or custom C++ dependencies.
|
| 56 |
+
|
| 57 |
+
### Installation
|
| 58 |
+
|
| 59 |
+
```bash
|
| 60 |
+
pip install torch safetensors huggingface_hub
|
| 61 |
+
```
|
| 62 |
+
|
| 63 |
+
### Inference Example
|
| 64 |
+
|
| 65 |
+
```python
|
| 66 |
+
import torch
|
| 67 |
+
from huggingface_hub import hf_hub_download
|
| 68 |
+
|
| 69 |
+
# Download modeling code and load weights
|
| 70 |
+
# Or copy modeling_xeus.py directly to your codebase
|
| 71 |
+
from modeling_xeus import XeusTrunk
|
| 72 |
+
|
| 73 |
+
# Automatically downloads model.safetensors from this repository
|
| 74 |
+
model = XeusTrunk.from_pretrained("giangndm/xeus")
|
| 75 |
+
model.eval()
|
| 76 |
+
|
| 77 |
+
# Input: 16 kHz waveform (batch_size, num_samples)
|
| 78 |
+
# Example: 1.0 second of dummy audio
|
| 79 |
+
audio = torch.randn(1, 16000)
|
| 80 |
+
|
| 81 |
+
with torch.no_grad():
|
| 82 |
+
# Shape: [1, 49, 1024] (50 Hz frame rate)
|
| 83 |
+
features = model(audio)
|
| 84 |
+
|
| 85 |
+
print("Acoustic representation shape:", features.shape)
|
| 86 |
+
```
|
| 87 |
+
|
| 88 |
+
---
|
| 89 |
+
|
| 90 |
+
## Weight Verification & Conversion Details
|
| 91 |
+
|
| 92 |
+
The weights in `model.safetensors` were converted directly from `model/xeus_checkpoint_new.pth` (commit `02acdd3ac9445561eeb7e9e7f096e4482a32b3a7`) of `espnet/xeus`.
|
| 93 |
+
- Output parity: **Exact bit-for-bit match (max numerical difference = 0.0)** compared to the original checkpoint.
|
| 94 |
+
- Tensors: All 763 tensors preserved in contiguous C-order format.
|
| 95 |
+
|
| 96 |
+
---
|
| 97 |
+
|
| 98 |
+
## License
|
| 99 |
+
|
| 100 |
+
This model and its weights are distributed under the **Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International (CC-BY-NC-SA 4.0)** license, matching the original license established by the authors at CMU WAVLab / ESPnet. See [`LICENSE`](LICENSE) for complete legal terms.
|
| 101 |
+
|
| 102 |
+
---
|
| 103 |
+
|
| 104 |
+
## Citation
|
| 105 |
+
|
| 106 |
+
```bibtex
|
| 107 |
+
@article{chen2024xeus,
|
| 108 |
+
title={XEUS: A Cross-lingual Encoder for Universal Speech},
|
| 109 |
+
author={Chen, Wan-Chi and Choi, Kwanghee and Kim, David and Watanabe, Shinji},
|
| 110 |
+
journal={arXiv preprint arXiv:2406.11832},
|
| 111 |
+
year={2024}
|
| 112 |
+
}
|
| 113 |
+
```
|
config.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"XeusTrunk"
|
| 4 |
+
],
|
| 5 |
+
"model_type": "xeus",
|
| 6 |
+
"hidden_dim": 1024,
|
| 7 |
+
"num_blocks": 19,
|
| 8 |
+
"linear_units": 4096,
|
| 9 |
+
"heads": 8,
|
| 10 |
+
"kernel": 31,
|
| 11 |
+
"sampling_rate": 16000,
|
| 12 |
+
"frame_rate_hz": 50.0,
|
| 13 |
+
"torch_dtype": "float32"
|
| 14 |
+
}
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f6010a004d2e7c3508bfb4d833566a5d8b85024818a83dff284c4684b361bb27
|
| 3 |
+
size 2306025584
|
modeling_xeus.py
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pure PyTorch implementation of the XEUS E-Branchformer acoustic foundation model.
|
| 2 |
+
|
| 3 |
+
Converted to SafeTensors format with zero external dependencies (no ESPnet installation required).
|
| 4 |
+
Original paper: XEUS - A Cross-lingual Encoder for Universal Speech (CMU WAVLab).
|
| 5 |
+
Weights repository: https://huggingface.co/giangndm/xeus
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import warnings
|
| 9 |
+
from typing import Optional
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
import torch.nn as nn
|
| 13 |
+
import torch.nn.functional as F
|
| 14 |
+
from huggingface_hub import hf_hub_download
|
| 15 |
+
from safetensors.torch import load_file
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class TransposeLayerNorm(nn.LayerNorm):
|
| 19 |
+
"""LayerNorm operating on channel dimension of (B, C, T) tensors."""
|
| 20 |
+
|
| 21 |
+
def forward(self, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 22 |
+
transposed = input_tensor.transpose(-2, -1)
|
| 23 |
+
normalized = F.layer_norm(
|
| 24 |
+
transposed, self.normalized_shape, self.weight, self.bias, self.eps
|
| 25 |
+
)
|
| 26 |
+
return normalized.transpose(-2, -1)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class ConvLayerBlock(nn.Module):
|
| 30 |
+
"""Convolutional downsampling block used in CNNFrontend."""
|
| 31 |
+
|
| 32 |
+
def __init__(
|
| 33 |
+
self,
|
| 34 |
+
in_channels: int,
|
| 35 |
+
out_channels: int,
|
| 36 |
+
kernel_size: int,
|
| 37 |
+
stride: int,
|
| 38 |
+
bias: bool = True,
|
| 39 |
+
) -> None:
|
| 40 |
+
super().__init__()
|
| 41 |
+
self.kernel_size = kernel_size
|
| 42 |
+
self.stride = stride
|
| 43 |
+
self.conv = nn.Conv1d(
|
| 44 |
+
in_channels, out_channels, kernel_size=kernel_size, stride=stride, bias=bias
|
| 45 |
+
)
|
| 46 |
+
self.layer_norm = TransposeLayerNorm(out_channels)
|
| 47 |
+
|
| 48 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 49 |
+
return F.gelu(self.layer_norm(self.conv(x)))
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class CNNFrontend(nn.Module):
|
| 53 |
+
"""Wav2Vec-style 7-layer convolutional feature extractor for 16kHz audio."""
|
| 54 |
+
|
| 55 |
+
def __init__(self) -> None:
|
| 56 |
+
super().__init__()
|
| 57 |
+
shapes = [
|
| 58 |
+
(512, 10, 5),
|
| 59 |
+
(512, 3, 2),
|
| 60 |
+
(512, 3, 2),
|
| 61 |
+
(512, 3, 2),
|
| 62 |
+
(512, 3, 2),
|
| 63 |
+
(512, 2, 2),
|
| 64 |
+
(512, 2, 2),
|
| 65 |
+
]
|
| 66 |
+
in_channels = 1
|
| 67 |
+
blocks = []
|
| 68 |
+
for out_channels, kernel_size, stride in shapes:
|
| 69 |
+
blocks.append(
|
| 70 |
+
ConvLayerBlock(
|
| 71 |
+
in_channels, out_channels, kernel_size=kernel_size, stride=stride
|
| 72 |
+
)
|
| 73 |
+
)
|
| 74 |
+
in_channels = out_channels
|
| 75 |
+
self.layers = nn.Sequential(*blocks)
|
| 76 |
+
|
| 77 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 78 |
+
if x.ndim == 2:
|
| 79 |
+
x = F.layer_norm(x, (x.shape[-1],))
|
| 80 |
+
x = x.unsqueeze(1)
|
| 81 |
+
first_weight = self.layers[0].conv.weight
|
| 82 |
+
if x.dtype != first_weight.dtype:
|
| 83 |
+
x = x.to(dtype=first_weight.dtype)
|
| 84 |
+
x = self.layers(x)
|
| 85 |
+
return x.transpose(1, 2)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class Preencoder(nn.Module):
|
| 89 |
+
"""Linear projection from frontend 512 dim to encoder 1024 dim."""
|
| 90 |
+
|
| 91 |
+
def __init__(self, in_dim: int = 512, out_dim: int = 1024) -> None:
|
| 92 |
+
super().__init__()
|
| 93 |
+
self.linear_out = nn.Linear(in_dim, out_dim)
|
| 94 |
+
|
| 95 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 96 |
+
return self.linear_out(x)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class ConvPositionalEmbedding(nn.Module):
|
| 100 |
+
"""Depthwise 1D convolutional relative positional embedding."""
|
| 101 |
+
|
| 102 |
+
def __init__(self, hidden_dim: int = 1024, kernel_size: int = 31) -> None:
|
| 103 |
+
super().__init__()
|
| 104 |
+
conv = nn.Conv1d(
|
| 105 |
+
hidden_dim,
|
| 106 |
+
hidden_dim,
|
| 107 |
+
kernel_size=kernel_size,
|
| 108 |
+
padding=(kernel_size - 1) // 2,
|
| 109 |
+
groups=16,
|
| 110 |
+
)
|
| 111 |
+
with warnings.catch_warnings():
|
| 112 |
+
warnings.simplefilter("ignore")
|
| 113 |
+
conv = nn.utils.weight_norm(conv, name="weight", dim=2)
|
| 114 |
+
self.convs = nn.ModuleList([conv])
|
| 115 |
+
|
| 116 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 117 |
+
residual = x
|
| 118 |
+
x = x.transpose(1, 2)
|
| 119 |
+
for conv in self.convs:
|
| 120 |
+
x = conv(x)
|
| 121 |
+
x = F.gelu(x)
|
| 122 |
+
x = x.transpose(1, 2)
|
| 123 |
+
return residual + x
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
class CSGU(nn.Module):
|
| 127 |
+
"""Convolutional Spatial Gating Unit."""
|
| 128 |
+
|
| 129 |
+
def __init__(self, size: int = 3072, kernel_size: int = 31) -> None:
|
| 130 |
+
super().__init__()
|
| 131 |
+
self.norm = nn.LayerNorm(size // 2)
|
| 132 |
+
self.conv = nn.Conv1d(
|
| 133 |
+
size // 2,
|
| 134 |
+
size // 2,
|
| 135 |
+
kernel_size=kernel_size,
|
| 136 |
+
padding=(kernel_size - 1) // 2,
|
| 137 |
+
groups=size // 2,
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 141 |
+
u, v = x.chunk(2, dim=-1)
|
| 142 |
+
v = self.norm(v)
|
| 143 |
+
v = v.transpose(1, 2)
|
| 144 |
+
v = self.conv(v)
|
| 145 |
+
v = v.transpose(1, 2)
|
| 146 |
+
return u * v
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class ConvolutionalGatingMLP(nn.Module):
|
| 150 |
+
"""Branch containing CSGU gated linear unit and depthwise conv."""
|
| 151 |
+
|
| 152 |
+
def __init__(
|
| 153 |
+
self, size: int = 1024, linear_units: int = 3072, kernel_size: int = 31
|
| 154 |
+
) -> None:
|
| 155 |
+
super().__init__()
|
| 156 |
+
self.channel_proj1 = nn.Linear(size, linear_units)
|
| 157 |
+
self.csgu = CSGU(linear_units, kernel_size)
|
| 158 |
+
self.channel_proj2 = nn.Linear(linear_units // 2, size)
|
| 159 |
+
|
| 160 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 161 |
+
x = self.channel_proj1(x)
|
| 162 |
+
x = F.gelu(x)
|
| 163 |
+
x = self.csgu(x)
|
| 164 |
+
return self.channel_proj2(x)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
class MultiHeadedAttention(nn.Module):
|
| 168 |
+
"""Multi-Head Self-Attention with projection matrices."""
|
| 169 |
+
|
| 170 |
+
def __init__(self, n_head: int = 8, n_feat: int = 1024) -> None:
|
| 171 |
+
super().__init__()
|
| 172 |
+
self.d_k = n_feat // n_head
|
| 173 |
+
self.h = n_head
|
| 174 |
+
self.linear_q = nn.Linear(n_feat, n_feat)
|
| 175 |
+
self.linear_k = nn.Linear(n_feat, n_feat)
|
| 176 |
+
self.linear_v = nn.Linear(n_feat, n_feat)
|
| 177 |
+
self.linear_out = nn.Linear(n_feat, n_feat)
|
| 178 |
+
|
| 179 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 180 |
+
b, t, d = x.shape
|
| 181 |
+
q = self.linear_q(x).view(b, t, self.h, self.d_k).transpose(1, 2)
|
| 182 |
+
k = self.linear_k(x).view(b, t, self.h, self.d_k).transpose(1, 2)
|
| 183 |
+
v = self.linear_v(x).view(b, t, self.h, self.d_k).transpose(1, 2)
|
| 184 |
+
out = F.scaled_dot_product_attention(q, k, v)
|
| 185 |
+
out = out.transpose(1, 2).contiguous().view(b, t, d)
|
| 186 |
+
return self.linear_out(out)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
class EBranchformerEncoderLayer(nn.Module):
|
| 190 |
+
"""Single E-Branchformer layer combining Attn, CGMLP and FFN branches."""
|
| 191 |
+
|
| 192 |
+
def __init__(
|
| 193 |
+
self,
|
| 194 |
+
size: int = 1024,
|
| 195 |
+
linear_units: int = 4096,
|
| 196 |
+
cgmlp_units: int = 3072,
|
| 197 |
+
heads: int = 8,
|
| 198 |
+
kernel: int = 31,
|
| 199 |
+
) -> None:
|
| 200 |
+
super().__init__()
|
| 201 |
+
self.norm_mha = nn.LayerNorm(size)
|
| 202 |
+
self.norm_mlp = nn.LayerNorm(size)
|
| 203 |
+
self.mha = MultiHeadedAttention(heads, size)
|
| 204 |
+
self.cgmlp = ConvolutionalGatingMLP(size, cgmlp_units, kernel)
|
| 205 |
+
self.norm_merge = nn.LayerNorm(size)
|
| 206 |
+
self.merge_proj = nn.Linear(size + size, size)
|
| 207 |
+
self.norm_ffn = nn.LayerNorm(size)
|
| 208 |
+
self.ffn = nn.Sequential(
|
| 209 |
+
nn.Linear(size, linear_units),
|
| 210 |
+
nn.GELU(),
|
| 211 |
+
nn.Linear(linear_units, size),
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 215 |
+
# Branch 1: MHA
|
| 216 |
+
branch1 = self.mha(self.norm_mha(x))
|
| 217 |
+
# Branch 2: CGMLP
|
| 218 |
+
branch2 = self.cgmlp(self.norm_mlp(x))
|
| 219 |
+
# Merge branches
|
| 220 |
+
merged = torch.cat([branch1, branch2], dim=-1)
|
| 221 |
+
merged = self.merge_proj(merged)
|
| 222 |
+
x = x + self.norm_merge(merged)
|
| 223 |
+
# FFN sublayer
|
| 224 |
+
x = x + self.ffn(self.norm_ffn(x))
|
| 225 |
+
return x
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
class EBranchformerEncoder(nn.Module):
|
| 229 |
+
"""Stack of E-Branchformer blocks with relative positional embeddings."""
|
| 230 |
+
|
| 231 |
+
def __init__(
|
| 232 |
+
self,
|
| 233 |
+
num_blocks: int = 19,
|
| 234 |
+
size: int = 1024,
|
| 235 |
+
linear_units: int = 4096,
|
| 236 |
+
heads: int = 8,
|
| 237 |
+
kernel: int = 31,
|
| 238 |
+
) -> None:
|
| 239 |
+
super().__init__()
|
| 240 |
+
self.embed = nn.Sequential(ConvPositionalEmbedding(size, kernel))
|
| 241 |
+
self.encoders = nn.ModuleList([
|
| 242 |
+
EBranchformerEncoderLayer(size, linear_units, 3072, heads, kernel)
|
| 243 |
+
for _ in range(num_blocks)
|
| 244 |
+
])
|
| 245 |
+
self.after_norm = nn.LayerNorm(size)
|
| 246 |
+
self.gradient_checkpointing = False
|
| 247 |
+
|
| 248 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 249 |
+
x = self.embed(x)
|
| 250 |
+
for layer in self.encoders:
|
| 251 |
+
if self.gradient_checkpointing and self.training:
|
| 252 |
+
x = torch.utils.checkpoint.checkpoint(layer, x, use_reentrant=False)
|
| 253 |
+
else:
|
| 254 |
+
x = layer(x)
|
| 255 |
+
return self.after_norm(x)
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
class XeusTrunk(nn.Module):
|
| 259 |
+
"""Complete XEUS acoustic foundation trunk (Frontend + Preencoder + EBranchformer)."""
|
| 260 |
+
|
| 261 |
+
DEFAULT_REPO_ID = "giangndm/xeus"
|
| 262 |
+
DEFAULT_FILENAME = "model.safetensors"
|
| 263 |
+
|
| 264 |
+
def __init__(
|
| 265 |
+
self,
|
| 266 |
+
num_blocks: int = 19,
|
| 267 |
+
hidden_dim: int = 1024,
|
| 268 |
+
linear_units: int = 4096,
|
| 269 |
+
heads: int = 8,
|
| 270 |
+
kernel: int = 31,
|
| 271 |
+
) -> None:
|
| 272 |
+
super().__init__()
|
| 273 |
+
self.frontend = CNNFrontend()
|
| 274 |
+
self.preencoder = Preencoder(512, hidden_dim)
|
| 275 |
+
self.encoder = EBranchformerEncoder(
|
| 276 |
+
num_blocks, hidden_dim, linear_units, heads, kernel
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 280 |
+
x = self.frontend(x)
|
| 281 |
+
x = self.preencoder(x)
|
| 282 |
+
return self.encoder(x)
|
| 283 |
+
|
| 284 |
+
@classmethod
|
| 285 |
+
def from_pretrained(
|
| 286 |
+
cls,
|
| 287 |
+
repo_id: str = DEFAULT_REPO_ID,
|
| 288 |
+
revision: Optional[str] = None,
|
| 289 |
+
filename: str = DEFAULT_FILENAME,
|
| 290 |
+
) -> "XeusTrunk":
|
| 291 |
+
model = cls()
|
| 292 |
+
ckpt_path = hf_hub_download(repo_id=repo_id, revision=revision, filename=filename)
|
| 293 |
+
if filename.endswith(".safetensors"):
|
| 294 |
+
state_dict = load_file(ckpt_path)
|
| 295 |
+
else:
|
| 296 |
+
state_dict = torch.load(ckpt_path, map_location="cpu", weights_only=True)
|
| 297 |
+
filtered_state = {
|
| 298 |
+
k: v
|
| 299 |
+
for k, v in state_dict.items()
|
| 300 |
+
if k.startswith(("frontend.", "preencoder.", "encoder."))
|
| 301 |
+
}
|
| 302 |
+
model.load_state_dict(filtered_state, strict=True)
|
| 303 |
+
return model
|