├── .gitignore ├── CITATION.cff ├── LICENSE ├── README.md ├── app.py ├── assets ├── speechllm.png └── streamlit_app.png ├── data_samples ├── dev.csv └── train.csv ├── dataset.py ├── huggingface ├── hf_repo │ ├── __init__.py │ ├── config.py │ └── model.py ├── push_to_hub.ipynb └── save_checkpoint.py ├── model ├── __pycache__ │ ├── connector.cpython-311.pyc │ ├── encoder.cpython-311.pyc │ └── llm.cpython-311.pyc ├── connector.py ├── encoder.py └── llm.py ├── requirements.txt ├── test.py ├── train.py └── trainer.py /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__/* 2 | checkpoints/* 3 | 4 | -------------------------------------------------------------------------------- /CITATION.cff: -------------------------------------------------------------------------------- 1 | cff-version: 1.2.0 2 | message: "If you use this model, please cite it using these metadata." 3 | authors: 4 | - family-names: "Rajaa" 5 | given-names: "Shangeth" 6 | - family-names: "Tushar" 7 | given-names: "Abhinav" 8 | 9 | title: "SpeechLLM: Multi-Modal LLM for Speech Understanding" 10 | abstract : "" 11 | type: model 12 | keywords: 13 | - "multi-modal-llms" 14 | - "llm" 15 | - "speech" 16 | - "conversational-ai" 17 | version: 1.0.0 18 | date-released: 2024-25-06 19 | url: "https://github.com/skit-ai/SpeechLLM" 20 | license: Apache-2.0 21 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SpeechLLM 2 | 3 | [![hf_model](https://img.shields.io/badge/🤗-SpeechLLM%20HuggingFace-blue.svg)](https://huggingface.co/collections/skit-ai/speechllm-66605bfb37a54d4e4a60efe2) 4 | [![Code License](https://img.shields.io/badge/Code%20License-Apache_2.0-green.svg)](https://github.com/skit-ai/SpeechLLM/blob/main/LICENSE) 5 | [![github](https://img.shields.io/badge/-Github-black?logo=github)](https://github.com/skit-ai/SpeechLLM.git)[![GitHub stars](https://img.shields.io/github/stars/skit-ai/SpeechLLM?style=social)](https://github.com/skit-ai/SpeechLLM/stargazers) 6 | [![Open in Colab](https://img.shields.io/badge/Open%20in%20Colab-F9AB00?logo=googlecolab&color=blue)](https://colab.research.google.com/drive/1uqhRl36LJKA4IxnrhplLMv0wQ_f3OuBM?usp=sharing) 7 | 8 | 9 | 10 | ![](./assets/speechllm.png) 11 | 12 | SpeechLLM is a multi-modal Language Model (LLM) specifically trained to analyze and predict metadata from a speaker's turn in a conversation. This advanced model integrates a speech encoder to transform speech signals into meaningful speech representations. These embeddings, combined with text instructions, are then processed by the LLM to generate predictions. 13 | 14 | The model inputs an speech audio file of **16 KHz** and predicts the following: 15 | 1. **SpeechActivity** : if the audio signal contains speech (True/False) 16 | 2. **Transcript** : ASR transcript of the audio 17 | 3. **Gender** of the speaker (Female/Male) 18 | 4. **Age** of the speaker (Young/Middle-Age/Senior) 19 | 5. **Accent** of the speaker (Africa/America/Celtic/Europe/Oceania/South-Asia/South-East-Asia) 20 | 6. **Emotion** of the speaker (Happy/Sad/Anger/Neutral/Frustrated) 21 | 22 | ## Usage 23 | ```python 24 | # Load model directly from huggingface 25 | from transformers import AutoModel 26 | model = AutoModel.from_pretrained("skit-ai/speechllm-2B", trust_remote_code=True) 27 | 28 | model.generate_meta( 29 | audio_path="path-to-audio.wav", #16k Hz, mono 30 | audio_tensor=torchaudio.load("path-to-audio.wav")[1], # [Optional] either audio_path or audio_tensor directly 31 | instruction="Give me the following information about the audio [SpeechActivity, Transcript, Gender, Emotion, Age, Accent]", 32 | max_new_tokens=500, 33 | return_special_tokens=False 34 | ) 35 | 36 | # Model Generation 37 | ''' 38 | { 39 | "SpeechActivity" : "True", 40 | "Transcript": "Yes, I got it. I'll make the payment now.", 41 | "Gender": "Female", 42 | "Emotion": "Neutral", 43 | "Age": "Young", 44 | "Accent" : "America", 45 | } 46 | ''' 47 | ``` 48 | 49 | Try the model in [Google Colab Notebook](https://colab.research.google.com/drive/1uqhRl36LJKA4IxnrhplLMv0wQ_f3OuBM?usp=sharing). Also, check out our [blog](https://tech.skit.ai/speech-conversational-llms/) on SpeechLLM for end-to-end conversational agents(User Speech -> Response). 50 | 51 | ## Model Weights 52 | We released the speechllm-2B and speechllm-1.5B model checkpoints on huggingface :hugs:. 53 | | **Model** | **Speech Encoder** | **LLM** | checkpoint url | 54 | |-------------------|-------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------|---------------------------------------------------------------| 55 | | **speechllm-2B** | [facebook/hubert-xlarge-ll60k](https://huggingface.co/facebook/hubert-xlarge-ll60k) | [TinyLlama/TinyLlama-1.1B-Chat-v1.0](https://huggingface.co/TinyLlama/TinyLlama-1.1B-Chat-v1.0) | [Huggingface](https://huggingface.co/skit-ai/speechllm-2B) | 56 | | **speechllm-1.5B** | [microsoft/wavlm-large](https://huggingface.co/microsoft/wavlm-large) | [ TinyLlama/TinyLlama-1.1B-Chat-v1.0 ]( https://huggingface.co/TinyLlama/TinyLlama-1.1B-Chat-v1.0) | [Huggingface]( https://huggingface.co/skit-ai/speechllm-1.5B) | 57 | 58 | ## Latest Checkpoint Result 59 | 60 | ### speechllm-2B 61 | | **Dataset** | **Type** | **Word Error Rate** | **Gender Acc** | **Age Acc** | **Accent Acc** | 62 | |:--------------------------:|:-------------------:|:-------------------:|:--------------:|:-----------:|:--------------:| 63 | | **librispeech-test-clean** | Read Speech | 6.73 | 0.9496 | | | 64 | | **librispeech-test-other** | Read Speech | 9.13 | 0.9217 | | | 65 | | **CommonVoice test** | Diverse Accent, Age | 25.66 | 0.8680 | 0.6041 | 0.6959 | 66 | 67 | ### speechllm-1.5B 68 | | **Dataset** | **Type** | **Word Error Rate** | **Gender Acc** | **Age Acc** | **Accent Acc** | 69 | |:--------------------------:|:-------------------:|:-------------------:|:--------------:|:-----------:|:--------------:| 70 | | **librispeech-test-clean** | Read Speech | 11.51 | 0.9594 | | | 71 | | **librispeech-test-other** | Read Speech | 16.68 | 0.9297 | | | 72 | | **CommonVoice test** | Diverse Accent, Age | 26.02 | 0.9476 | 0.6498 | 0.8121 | 73 | 74 | 75 | ## Training 76 | 77 | ### Dataset Preparation and Installation 78 | Install the necessary packages in the requirements.txt and take care of CUDA versions. Then prepare the audio dataset similar to data_samples/train.csv and data_samples/dev.csv, if new tasks eg: (noise, environment class) has to be added, then update the dataset.py accordingly. 79 | ```bash 80 | pip install requirements.txt 81 | ``` 82 | 83 | ### Train 84 | update the config in train.py, such as audio_encoder_name, llm_name, etc and other hyper parameters. 85 | ```bash 86 | python train.py 87 | ``` 88 | 89 | ### Evaluation 90 | After training, update checkpoint path and test dataset path(similar format to train/dev.csv). 91 | ```bash 92 | python test.py 93 | ``` 94 | 95 | ### Infer model in Streamlit app 96 | ```bash 97 | streamlit run app.py 98 | ``` 99 | ![](./assets/streamlit_app.png) 100 | 101 | 102 | ## Disclaimer 103 | The models provided in this repository are not perfect and may produce errors in Automatic Speech Recognition (ASR), gender identification, age estimation, accent recognition, and emotion detection. Additionally, these models may exhibit biases related to gender, age, accent, and emotion. Please use with caution, especially in production environments, and be aware of potential inaccuracies and biases. 104 | 105 | ## License 106 | This project is released under the Apache 2.0 license as found in the LICENSE file. The released checkpoints, and code are intended for research purpose subject to the license of [facebook/hubert-xlarge-ll60k](https://huggingface.co/facebook/hubert-xlarge-ll60k), [microsoft/wavlm-large](https://huggingface.co/microsoft/wavlm-large) and [ TinyLlama/TinyLlama-1.1B-Chat-v1.0 ]( https://huggingface.co/TinyLlama/TinyLlama-1.1B-Chat-v1.0) models. 107 | 108 | ## Cite 109 | ``` 110 | @misc{Rajaa_SpeechLLM_Multi-Modal_LLM, 111 | author = {Rajaa, Shangeth and Tushar, Abhinav}, 112 | title = {{SpeechLLM: Multi-Modal LLM for Speech Understanding}}, 113 | url = {https://github.com/skit-ai/SpeechLLM} 114 | } 115 | ``` 116 | -------------------------------------------------------------------------------- /app.py: -------------------------------------------------------------------------------- 1 | import streamlit as st 2 | import torchaudio 3 | import io 4 | import matplotlib.pyplot as plt 5 | # Assuming audio_recorder_streamlit is a custom or third-party module for recording audio in Streamlit apps 6 | from audio_recorder_streamlit import audio_recorder 7 | from trainer import SpeechLLMLightning 8 | import re 9 | import json 10 | import sys 11 | 12 | def load_model(ckpt_path): 13 | model = SpeechLLMLightning.load_from_checkpoint(ckpt_path) 14 | tokenizer = model.llm_tokenizer 15 | model.eval() 16 | model.freeze() 17 | model.to('cuda') 18 | return model, tokenizer 19 | 20 | def get_or_load_model(ckpt_path): 21 | if 'model' not in st.session_state or 'tokenizer' not in st.session_state: 22 | model = SpeechLLMLightning.load_from_checkpoint(ckpt_path) 23 | tokenizer = model.llm_tokenizer 24 | model.eval() 25 | model.freeze() 26 | model.to('cuda') 27 | st.session_state.model = model 28 | st.session_state.tokenizer = tokenizer 29 | return st.session_state.model, st.session_state.tokenizer 30 | 31 | def extract_dictionary(input_string): 32 | # Extract the JSON-like string 33 | json_str_match = re.search(r'\{.*\}', input_string) 34 | if not json_str_match: 35 | print(input_string) 36 | return "No valid JSON found." 37 | 38 | json_str = json_str_match.group(0) 39 | 40 | # Attempt to fix common JSON formatting issues: 41 | # 1. Ensure property names are enclosed in double quotes. 42 | # 2. Remove trailing commas before closing braces or brackets. 43 | json_str = re.sub(r'(?<=\{|\,)\s*([^\"{}\[\]\s]+)\s*:', r'"\1":', json_str) # Fix unquoted keys 44 | json_str = re.sub(r',\s*([\}\]])', r'\1', json_str) # Remove trailing commas 45 | 46 | try: 47 | # Parse the corrected JSON string into a dictionary 48 | data_dict = json.loads(json_str) 49 | return data_dict 50 | except json.JSONDecodeError as e: 51 | # Return an error message if JSON parsing fails 52 | return f"Error parsing JSON: {str(e)}" 53 | 54 | # Function to generate a response from the model 55 | def generate_response(wav, model, tokenizer): 56 | pre_speech_prompt = '''Instruction: 57 | Give me the following information about the audio [SpeechActivity, Transcript, Gender, Age, Emotion, Accent] 58 | 59 | Input: 60 | ''' 61 | 62 | post_speech_prompt = ''' 63 | 64 | Output:''' 65 | 66 | output_prompt = '\n' 67 | 68 | pre_tokenized_ids = tokenizer(pre_speech_prompt, padding="do_not_pad", return_tensors='pt', truncation=False, add_special_tokens=False)["input_ids"] 69 | post_tokenized_ids = tokenizer(post_speech_prompt, padding="do_not_pad", return_tensors='pt', truncation=False, add_special_tokens=False)["input_ids"] 70 | output_tokenized_ids = tokenizer(output_prompt, padding="do_not_pad", return_tensors='pt', truncation=False, add_special_tokens=False)["input_ids"] 71 | 72 | combined_embeds, atts, label_ids = model.encode(wav.cuda(), pre_tokenized_ids.cuda(), post_tokenized_ids.cuda(), output_tokenized_ids.cuda()) 73 | out = model.llm_model.generate( 74 | inputs_embeds=combined_embeds, 75 | max_new_tokens=2000, 76 | ).cpu().tolist()[0] 77 | 78 | output_text = tokenizer.decode(out, skip_special_tokens=True) 79 | return output_text 80 | 81 | 82 | if __name__ == "__main__": 83 | model, tokenizer = get_or_load_model("path-to-best_checkpoint.ckpt") 84 | 85 | # Streamlit UI components 86 | st.title("SpeechLLM : Multi-Modal LLM for Speech Understanding") 87 | 88 | st.markdown(""" 89 | [![hf_model](https://img.shields.io/badge/🤗-SpeechLLM%20HuggingFace-blue.svg)](https://huggingface.co/collections/skit-ai/speechllm-66605bfb37a54d4e4a60efe2) 90 | [![Code License](https://img.shields.io/badge/Code%20License-Apache_2.0-green.svg)](https://github.com/skit-ai/SpeechLLM/blob/main/LICENSE) 91 | [![github](https://img.shields.io/badge/-Github-black?logo=github)](https://github.com/skit-ai/SpeechLLM.git) 92 | [![GitHub stars](https://img.shields.io/github/stars/skit-ai/SpeechLLM?style=social)](https://github.com/skit-ai/SpeechLLM/stargazers) 93 | [![Open in Colab](https://img.shields.io/badge/Open%20in%20Colab-F9AB00?logo=googlecolab&color=blue)](https://colab.research.google.com/drive/1uqhRl36LJKA4IxnrhplLMv0wQ_f3OuBM?usp=sharing) 94 | """, unsafe_allow_html=True) 95 | 96 | st.write("Click below to record an audio file to get its transcription and other metadata.") 97 | 98 | # Improved layout for audio recording button 99 | col1, col2, col3 = st.columns([1, 2, 1]) 100 | with col2: 101 | st.write("###") 102 | st.write("###") 103 | audio_data = audio_recorder(sample_rate=16000, text="") 104 | # st.write("Click to record") 105 | 106 | # Transcription process 107 | if audio_data is not None: 108 | with st.spinner('Transcribing...'): 109 | try: 110 | # Load audio data into a tensor 111 | audio_buffer = io.BytesIO(audio_data) 112 | st.audio(audio_data, format='audio/wav', start_time=0) 113 | wav_tensor, sample_rate = torchaudio.load(audio_buffer) 114 | wav_tensor = wav_tensor.to('cuda').mean(0).unsqueeze(0) # mean of dual channel, remove if audio is mono 115 | 116 | # Process audio to get transcription 117 | transcription = generate_response(wav_tensor.cuda(), model, tokenizer) 118 | 119 | # Display the transcription 120 | st.success('Transcription Complete') 121 | st.text_area("LLM Output:", value=extract_dictionary(transcription), height=200, max_chars=None) 122 | # st.code(extract_dictionary(transcription), language='python') 123 | except Exception as e: 124 | st.error(f"An error occurred during transcription: {e}") 125 | -------------------------------------------------------------------------------- /assets/speechllm.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/skit-ai/SpeechLLM/f44d361277ae5e2fa687b39f861f630ca2571318/assets/speechllm.png -------------------------------------------------------------------------------- /assets/streamlit_app.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/skit-ai/SpeechLLM/f44d361277ae5e2fa687b39f861f630ca2571318/assets/streamlit_app.png -------------------------------------------------------------------------------- /data_samples/dev.csv: -------------------------------------------------------------------------------- 1 | dataset,set,audio_path,isspeech,transcript,gender,emotion,age,accent,audio_len 2 | ARCA23K,dev,path-to-audio.wav,False,__unknown__,__unknown__,__unknown__,__unknown__,__unknown__,5.146122448979592 3 | ARCA23K,dev,path-to-audio.wav,False,__unknown__,__unknown__,__unknown__,__unknown__,__unknown__,0.893968253968254 4 | CREMA-D,dev,path-to-audio.wav,True,I think I've seen this before,Male,Happy,middle-age,,2.402375 5 | CREMA-D,dev,path-to-audio.wav,True,I think I have a doctor's appointment,Male,Fearful,senior,,2.969625 6 | CommonVoice,dev,path-to-audio.wav,True,A ritzy limousine was driving along the fifth avenue.,Male,,young,Celtic,4.948125 7 | CommonVoice,dev,path-to-audio.wav,True,Something gets knocked down by a bulldozer.,Male,,young,America,3.988125 8 | LibriSpeech,dev-clean,path-to-audio.wav,True,FRIED BREAD FOR BORDERS,Female,,,,2.36 9 | LibriSpeech,dev-other,path-to-audio.wav,True,HOW CAN YOU SPEAK SO CRUELLY TO ME SHE ASKED,Female,,,,3.075 10 | MLSpokenWords,dev,path-to-audio.wav,True,stop,Female,,,,1.0 11 | MLSpokenWords,dev,path-to-audio.wav,True,down,Male,,,,1.0 12 | RAVDESS,dev,path-to-audio.wav,True,Dogs are sitting by the door,Female,Sad,,,3.370041666666667 13 | RAVDESS,dev,path-to-audio.wav,True,Dogs are sitting by the door,Female,Surprised,,,3.3033125 14 | -------------------------------------------------------------------------------- /data_samples/train.csv: -------------------------------------------------------------------------------- 1 | dataset,set,audio_path,isspeech,transcript,gender,emotion,age,accent,audio_len 2 | ARCA23K,train,path-to-audio.wav,False,__unknown__,__unknown__,__unknown__,__unknown__,__unknown__,0.953469387755102 3 | ARCA23K,train,path-to-audio.wav,False,__unknown__,__unknown__,__unknown__,__unknown__,__unknown__,0.4072335600907029 4 | ARCA23K,train,path-to-audio.wav,False,__unknown__,__unknown__,__unknown__,__unknown__,__unknown__,5.369387755102041 5 | ARCA23K,train,path-to-audio.wav,False,__unknown__,__unknown__,__unknown__,__unknown__,__unknown__,7.0 6 | ARCA23K,train,path-to-audio.wav,False,__unknown__,__unknown__,__unknown__,__unknown__,__unknown__,0.5535374149659864 7 | CREMA-D,train,path-to-audio.wav,True,I'm on my way to the meeting,Male,Angry,young,,2.3356875 8 | CREMA-D,train,path-to-audio.wav,True,I think I have a doctor's appointment,Female,Neutral,middle-age,,2.535875 9 | CREMA-D,train,path-to-audio.wav,True,That is exactly what happened,Female,Neutral,middle-age,,2.1354375 10 | CREMA-D,train,path-to-audio.wav,True,The surface is slick,Male,Neutral,middle-age,,2.43575 11 | CREMA-D,train,path-to-audio.wav,True,I'm on my way to the meeting,Female,Sad,middle-age,,2.7026875 12 | CommonVoice,train,path-to-audio.wav,True,"The game, I mean?",Female,,middle-age,Oceania,3.0675 13 | CommonVoice,train,path-to-audio.wav,True,These systems obligate unemployed people to undertake work that is beneficial to their community.,Female,,senior,America,7.061625 14 | CommonVoice,train,path-to-audio.wav,True,The Tribute Communities Centre was constructed to replace the Oshawa Civic Auditorium.,Male,,young,America,4.5435 15 | CommonVoice,train,path-to-audio.wav,True,He appears to have influenced Rainaldetto di Ranuccio of Spoleto.,Male,,middle-age,America,6.1275 16 | CommonVoice,train,path-to-audio.wav,True,The game is currently in its third edition.,Male,,middle-age,Oceania,4.349625 17 | IEMOCAP,train,path-to-audio.wav,True,"No. You can't think that way. I mean it's good--it's good that you're--that you're calling, you know. you can't",Male,Neutral,,,6.29025 18 | IEMOCAP,train,path-to-audio.wav,True,"We could get a good debate going about this, don't you think? Intemperate tots.",Male,Angry,,,4.2199375 19 | IEMOCAP,train,path-to-audio.wav,True,"Oh See, I don't care what you do, see. You can paint yourself green and run naked through the Place Vendome and run off with all of the men of the world. I shan't say a word, just as long as you love me best.",Male,Happy,,,16.6299375 20 | IEMOCAP,train,path-to-audio.wav,True,"No, you'll never forget him.",Male,Neutral,,,2.1560625 21 | IEMOCAP,train,path-to-audio.wav,True,Look that bag has my entire life in it and you just lost it.,Female,Frustrated,,,7.5 22 | LibriSpeech,train-clean-100,path-to-audio.wav,True,BUT HE COULD NOT GET OFF THE GROUND WHAT IS IT REDCOAT HAS SOMETHING HAPPENED TO YOU IT IS JUST PETER RABBIT YOU DON'T HAVE ANYTHING TO FEAR FROM ME CRIED PETER THE LOOK OF TERROR WHICH HAD BEEN IN THE EYES OF REDCOAT DIED OUT,Male,,,,15.745 23 | LibriSpeech,train-clean-100,path-to-audio.wav,True,A WHAT STAMMERED PETER A CAST OFF SUIT OF CLOTHES FROM ANY MEMBER OF THE SNAKE FAMILY REPLIED CRESTY SOMEWHAT IMPATIENTLY NOW DON'T FORGET PETER I'VE GOT TO GO HOUSE HUNTING BUT YOU'LL FIND ME THERE OR HEREABOUTS IF IT HAPPENS THAT YOU FIND ONE OF THOSE,Male,,,,16.55 24 | LibriSpeech,train-clean-100,path-to-audio.wav,True,THE WORD ITSELF CANNOT BE ADEQUATELY RENDERED BY ANY ENGLISH WORD FOR IT IS USED IN RELATION TO MANY KINDS OF MIMETIC MAGIC AS WELL AS IN RELATION TO THE PERFORMANCE OF MANY RELIGIOUS ACTS OF FAITH,Male,,,,10.925 25 | LibriSpeech,train-clean-100,path-to-audio.wav,True,BUT IF A FELLER KNOWS THE COUNTRY AND KEEPS HIS HEAD LEVEL HE CAN'T LOSE JEFFERSON HAD LOOKED AT SO MANY PROSPECTUSES AND SO MANY PICTURES OF MINES AND PINE TREES AND SMELTERS THAT I THINK HE'D FORGOTTEN THAT HE'D NEVER BEEN IN THE COUNTRY ANYWAY WHAT'S TWO HUNDRED MILES,Male,,,,14.935 26 | LibriSpeech,train-clean-100,path-to-audio.wav,True,A SURE SIGN SHE WAS PERPLEXED MERELY A BOY TO SEE AFTER THE FOWLS AND TO WAIT ABOUT THE HOUSE WHEN NECESSARY I LOVE FOWLS SAID JERRY SWEETLY AND LOOKING AS INNOCENT AS A BABE AND DOGS AND THINGS LIKE THAT,Male,,,,16.37 27 | MLSpokenWords,train,path-to-audio.wav,True,seven,Male,,,,1.0 28 | MLSpokenWords,train,path-to-audio.wav,True,nine,Female,,,,1.0 29 | MLSpokenWords,train,path-to-audio.wav,True,eight,Female,,,,1.0 30 | MLSpokenWords,train,path-to-audio.wav,True,right,Male,,,,1.0 31 | MLSpokenWords,train,path-to-audio.wav,True,seven,Female,,,,1.0 32 | RAVDESS,train,path-to-audio.wav,True,Kids are talking by the door,Male,Neutral,,,3.370041666666667 33 | RAVDESS,train,path-to-audio.wav,True,Kids are talking by the door,Female,Happy,,,3.536875 34 | RAVDESS,train,path-to-audio.wav,True,Dogs are sitting by the door,Female,Sad,,,3.670333333333333 35 | RAVDESS,train,path-to-audio.wav,True,Dogs are sitting by the door,Female,Sad,,,3.8038125 36 | RAVDESS,train,path-to-audio.wav,True,Kids are talking by the door,Female,Angry,,,3.670333333333333 37 | -------------------------------------------------------------------------------- /dataset.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from transformers import AutoProcessor, AutoFeatureExtractor 3 | 4 | import torch 5 | from torch.utils.data import Dataset 6 | import torchaudio 7 | import pandas as pd 8 | import random 9 | import numpy as np 10 | 11 | class MyCollator: 12 | def __init__(self, audio_encoder_name, tokenizer): 13 | self.audio_encoder_name = audio_encoder_name 14 | self.tokenizer = tokenizer 15 | self.hubert_processor = AutoFeatureExtractor.from_pretrained("microsoft/wavlm-base") # change according to the encoder 16 | 17 | def __call__(self, batch): 18 | waveform, pre_speech_prompt, post_speech_prompt, output_prompt, complete_prompt = batch[0] 19 | if waveform is not None: 20 | if "openai/whisper" in self.audio_encoder_name: 21 | mel = self.wav_2_mel(waveform).unsqueeze(0) 22 | else: 23 | mel = self.hubert_processor(waveform.squeeze(), return_tensors="pt", sampling_rate=16000).input_values 24 | else: 25 | mel = None 26 | 27 | pre_tokenized_ids = self.tokenizer(pre_speech_prompt, padding="do_not_pad", return_tensors='pt', truncation=False, add_special_tokens=False)["input_ids"] 28 | post_tokenized_ids = self.tokenizer(post_speech_prompt, padding="do_not_pad", return_tensors='pt', truncation=False, add_special_tokens=False)["input_ids"] 29 | output_tokenized_ids = self.tokenizer(self.tokenizer.bos_token + output_prompt + self.tokenizer.eos_token, padding="do_not_pad", return_tensors='pt', truncation=False, add_special_tokens=False)["input_ids"] 30 | 31 | return mel, pre_tokenized_ids, post_tokenized_ids, output_tokenized_ids 32 | 33 | def wav_2_mel(self, wav_tensor): 34 | mel = whisper.log_mel_spectrogram(wav_tensor[0]) 35 | return mel 36 | 37 | 38 | class AudioDataset(Dataset): 39 | def __init__(self, csv_file, mode='train', random_keys_prob=0.001): 40 | self.data_frame = pd.read_csv(csv_file) 41 | self.data_frame = self.data_frame.sample(frac=1, random_state=42).reset_index(drop=True) 42 | self.mode = mode 43 | self.random_keys_prob = random_keys_prob 44 | self.labels = ['isspeech', 'transcript', 'gender', 'emotion', 'age', 'accent'] 45 | 46 | def __len__(self): 47 | return len(self.data_frame) 48 | 49 | def __getitem__(self, idx): 50 | # Load audio 51 | audio_row = self.data_frame.iloc[idx] 52 | audio_path = audio_row['audio_path'] 53 | if pd.isna(audio_path): 54 | waveform = None 55 | else: 56 | waveform, sample_rate = torchaudio.load(audio_path) 57 | 58 | # Prepare labels dictionary based on mode and probability 59 | labels_str = {} 60 | if self.mode == 'train' and random.random() < self.random_keys_prob: 61 | random_labels = random.sample(self.labels, k=random.randint(1, len(self.labels))) 62 | for label in random_labels: 63 | if label in audio_row and pd.notnull(audio_row[label]): 64 | formatted_label = label.capitalize() 65 | if audio_row[label] == True or audio_row[label] == False: 66 | labels_str[formatted_label] = audio_row[label] 67 | else: 68 | labels_str[formatted_label] = str(audio_row[label]).lower() 69 | else: 70 | # Most of the time, include all available labels 71 | for label in self.labels: 72 | if label in audio_row and pd.notnull(audio_row[label]): 73 | formatted_label = label.capitalize() 74 | if audio_row[label] == True or audio_row[label] == False: 75 | labels_str[formatted_label] = audio_row[label] 76 | else: 77 | labels_str[formatted_label] = str(audio_row[label]).lower() 78 | 79 | 80 | if 'context' in audio_row.index: 81 | conv_history = audio_row['context'] 82 | else: 83 | conv_history = "" 84 | 85 | return waveform, labels_str, conv_history 86 | 87 | class InstructionalAudioDataset(AudioDataset): 88 | def __init__(self, csv_file, mode='train', random_keys_prob=0.1): 89 | """ 90 | Initialize the class with the specified CSV file, mode, and random keys probability. 91 | 92 | Args: 93 | csv_file (str): The path to the CSV file. 94 | mode (str, optional): The mode of the operation, defaults to 'train'. 95 | random_keys_prob (float, optional): The probability of using random keys, defaults to 0.1. 96 | 97 | Returns: 98 | None 99 | """ 100 | super().__init__(csv_file, mode, random_keys_prob) 101 | self.instruction_phrases = [ 102 | "Provide the details about the audio", 103 | "I need the following information from the audio", 104 | "Tell me about the audio regarding", 105 | "Extract the following details from the audio", 106 | "Give me the following information about the audio", 107 | "Provide details from the audio file", 108 | "I need information extracted from this speech", 109 | "Detail the contents of the following audio", 110 | "Share insights about this speech recording", 111 | "Describe the specifics captured in this audio file", 112 | "Summarize the audio's key information", 113 | "Convey the details embedded in this speech", 114 | "Outline the main points from this audio file", 115 | "Unpack the content of the following speech", 116 | "Present the facts from this audio recording", 117 | "Elucidate the elements within this speech", 118 | "Decipher the audio file's information", 119 | "Break down the details in this speech", 120 | "Analyze the following audio for details", 121 | "Report on the specifics of this speech file", 122 | "Transcribe the key points from this audio", 123 | "Explain the content of the speech recording", 124 | "Interpret the information within this audio file", 125 | "Catalog the details from this speech", 126 | "Narrate the findings in the audio", 127 | "Recount the specifics of this speech file", 128 | "Review the contents of the audio", 129 | "Assess the information provided by this speech", 130 | "Evaluate the details in the audio file", 131 | "Investigate the speech for key information", 132 | "Scrutinize the audio and provide insights", 133 | "Inspect the details within this speech", 134 | "Examine the audio file for specific information", 135 | "Survey the speech and detail your findings", 136 | "Study the audio and summarize the content", 137 | "Audit the speech for important details", 138 | "Appraise the audio file's key points", 139 | "Annotate the specifics found in the speech", 140 | "Dissect the audio to find important information", 141 | "Extract insights from the speech file", 142 | "Unveil the details in the audio recording", 143 | "Shed light on the speech's content", 144 | "Clarify the specifics within the audio file", 145 | "Illuminate the information in the speech", 146 | "Highlight the key points of the audio", 147 | "Reveal the contents captured in the speech file", 148 | "Uncover the details within the audio", 149 | "Delve into the speech for essential information", 150 | "Probe the audio file for details", 151 | "Explore the speech recording's specifics", 152 | "Research the contents of the audio", 153 | "Inquire into the details of the speech", 154 | "Sift through the audio for key information", 155 | "Dive into the speech to extract details", 156 | "Investigate the nuances of the audio file", 157 | "Give me the following information about the audio", 158 | "Fetch information", 159 | "Give me details about the audio", 160 | "what does this audio say", 161 | 'what is in the file', 162 | 'give me these details', 163 | ] 164 | 165 | def __getitem__(self, idx): 166 | waveform, labels_str, conv_history = super().__getitem__(idx) 167 | instruction_phrase = random.choice(self.instruction_phrases) 168 | 169 | pre_speech_prompt = f"Instruction:\n{instruction_phrase} - [" 170 | pre_speech_prompt += ', '.join(['IsSpeech' if k == 'isSpeech' else k for k in labels_str.keys()]) + "]\n\nInput:\n" 171 | pre_speech_prompt = pre_speech_prompt.replace("Isspeech", "SpeechActivity") 172 | post_speech_prompt = f"\n\n" + \ 173 | "Output:\n" 174 | output_prompt = "{" 175 | for key, value in labels_str.items(): 176 | if key=="Isspeech": key = 'SpeechActivity' 177 | output_prompt += f' "{key}": "{value}", ' 178 | output_prompt = output_prompt.rstrip(',\n') + "}" 179 | 180 | complete_prompt = pre_speech_prompt + post_speech_prompt + output_prompt 181 | return waveform, pre_speech_prompt, post_speech_prompt, output_prompt, complete_prompt 182 | 183 | 184 | # Example usage 185 | if __name__ == "__main__": 186 | dataset = InstructionalAudioDataset(csv_file='dev.csv', mode='test', random_keys_prob=0.0001) 187 | waveform, pre_speech_prompt, post_speech_prompt, output_prompt, complete_prompt = dataset[121] 188 | 189 | print(complete_prompt) 190 | print(waveform) 191 | -------------------------------------------------------------------------------- /huggingface/hf_repo/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/skit-ai/SpeechLLM/f44d361277ae5e2fa687b39f861f630ca2571318/huggingface/hf_repo/__init__.py -------------------------------------------------------------------------------- /huggingface/hf_repo/config.py: -------------------------------------------------------------------------------- 1 | from transformers import PretrainedConfig 2 | 3 | class SpeechLLMModelConfig(PretrainedConfig): 4 | model_type = "custom_model" 5 | 6 | def __init__(self, **kwargs): 7 | super().__init__(**kwargs) 8 | self.audio_enc_dim = 1024 9 | self.llm_dim = 2048 10 | 11 | self.audio_processor_name = "microsoft/wavlm-base" 12 | self.audio_encoder_name = 'microsoft/wavlm-large' 13 | self.llm_model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0" 14 | self.llm_model_checkpoint = "hf_repo/llm_model_checkpoint" 15 | -------------------------------------------------------------------------------- /huggingface/hf_repo/model.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | import torchaudio 4 | from transformers import PreTrainedModel, AutoModelForCausalLM, AutoTokenizer, HubertModel, AutoProcessor, AutoConfig, AutoModel, AutoFeatureExtractor 5 | from .config import SpeechLLMModelConfig 6 | from peft import LoraConfig, get_peft_model 7 | 8 | class TransformerAudioEnoder(nn.Module): 9 | def __init__(self, model_name='microsoft/wavlm-large', finetune=False): 10 | super().__init__() 11 | config = AutoConfig.from_pretrained(model_name) 12 | self.encoder = AutoModel.from_config(config) 13 | 14 | def forward(self, x): 15 | return self.encoder(x).last_hidden_state 16 | 17 | def return_device(self): 18 | return next(self.parameters()).device 19 | 20 | 21 | class CNNConnector(nn.Module): 22 | def __init__(self, in_channels, out_channels, k=2): 23 | super().__init__() 24 | self.layer = nn.Sequential( 25 | nn.ReLU(), 26 | nn.Conv1d(in_channels, out_channels//2, kernel_size=5, 27 | stride=1, padding=0), 28 | nn.ReLU(), 29 | nn.Conv1d(out_channels//2, out_channels, kernel_size=5, 30 | stride=k, padding=0), 31 | nn.ReLU(), 32 | nn.Conv1d(out_channels, out_channels, kernel_size=5, 33 | stride=1, padding=0), 34 | ) 35 | 36 | def forward(self, x): 37 | return self.layer(x.transpose(1,2)).transpose(1,2) 38 | 39 | 40 | class SpeechLLMModel(PreTrainedModel): 41 | config_class = SpeechLLMModelConfig 42 | 43 | def __init__(self, config): 44 | super().__init__(config) 45 | self.audio_processor = AutoFeatureExtractor.from_pretrained(config.audio_processor_name) 46 | self.audio_encoder = TransformerAudioEnoder(config.audio_encoder_name) 47 | self.connector = CNNConnector(config.audio_enc_dim, config.llm_dim) 48 | 49 | llm_config = AutoConfig.from_pretrained(config.llm_model_name) 50 | self.llm_model = AutoModelForCausalLM.from_config(llm_config) 51 | self.llm_tokenizer = AutoTokenizer.from_pretrained(config.llm_model_name) 52 | self.llm_tokenizer.pad_token = self.llm_tokenizer.eos_token 53 | 54 | peft_config = LoraConfig( 55 | r=8, 56 | lora_alpha=16, 57 | target_modules=['q_proj', 'k_proj', 'v_proj', 'o_proj', 'up_proj', 'down_proj', 'gate_proj'], 58 | lora_dropout=0.05, 59 | task_type="CAUSAL_LM", 60 | ) 61 | self.llm_model = get_peft_model(self.llm_model, peft_config) 62 | self.llm_model = self.llm_model.merge_and_unload() 63 | 64 | def encode(self, speech, pre_tokenized_ids, post_tokenized_ids, output_tokenized_ids): 65 | batch_size = speech.shape[0] 66 | 67 | with torch.no_grad(): 68 | speech_embeds = self.audio_encoder(speech) 69 | speech_embeds = self.connector(speech_embeds) 70 | 71 | embedder = self.llm_model.model.embed_tokens 72 | pre_prompt_embeds = embedder(pre_tokenized_ids) 73 | post_prompt_embeds = embedder(post_tokenized_ids) 74 | output_prompt_embeds = embedder(output_tokenized_ids) 75 | 76 | combined_embeds = torch.cat([pre_prompt_embeds, speech_embeds, post_prompt_embeds, output_prompt_embeds], dim=1) 77 | atts = torch.ones(combined_embeds.size()[:-1], dtype=torch.long).to(combined_embeds.device) 78 | 79 | input_token_length = pre_tokenized_ids.shape[1] + speech_embeds.shape[1] + post_tokenized_ids.shape[1] 80 | label_ids = torch.cat([ 81 | torch.ones([batch_size, input_token_length], device=combined_embeds.device) * -100, 82 | output_tokenized_ids 83 | ], 1).to(combined_embeds.device).to(torch.int64) 84 | return combined_embeds, atts, label_ids 85 | 86 | def forward(self, audio_tensor, pre_tokenized_ids, post_tokenized_ids, output_tokenized_ids, attention_mask=None): 87 | combined_embeds, atts, label_ids = self.encode(audio_tensor, pre_tokenized_ids, post_tokenized_ids, output_tokenized_ids) 88 | outputs = self.llm_model(inputs_embeds=combined_embeds, attention_mask=attention_mask) 89 | return outputs 90 | 91 | def generate_meta(self, audio_path=None, audio_tensor=None, instruction="Give me the following information about the audio [Transcript]", max_new_tokens=2000): 92 | device = self.audio_encoder.return_device() 93 | pre_speech_prompt = f'''Instruction: 94 | {instruction} 95 | 96 | Input: 97 | ''' 98 | post_speech_prompt = f''' 99 | 100 | Output:''' 101 | output_prompt = '\n' 102 | 103 | with torch.no_grad(): 104 | if audio_tensor == None and audio_path != None: 105 | audio_tensor, sr = torchaudio.load(audio_path) 106 | audio_tensor = self.audio_processor(audio_tensor.squeeze(), return_tensors="pt", sampling_rate=16000).input_values 107 | 108 | pre_tokenized_ids = self.llm_tokenizer(pre_speech_prompt, padding="do_not_pad", return_tensors='pt', truncation=False, add_special_tokens=False)["input_ids"] 109 | post_tokenized_ids = self.llm_tokenizer(post_speech_prompt, padding="do_not_pad", return_tensors='pt', truncation=False, add_special_tokens=False)["input_ids"] 110 | output_tokenized_ids = self.llm_tokenizer(output_prompt, padding="do_not_pad", return_tensors='pt', truncation=False, add_special_tokens=False)["input_ids"] 111 | 112 | combined_embeds, atts, label_ids = self.encode(audio_tensor.to(device), pre_tokenized_ids.to(device), post_tokenized_ids.to(device), output_tokenized_ids.to(device)) 113 | 114 | out = self.llm_model.generate( 115 | inputs_embeds=combined_embeds, 116 | max_new_tokens=max_new_tokens, 117 | pad_token_id=self.llm_tokenizer.pad_token_id 118 | ).cpu().tolist()[0] 119 | 120 | output_text = self.llm_tokenizer.decode(out, skip_special_tokens=True) 121 | return output_text 122 | 123 | -------------------------------------------------------------------------------- /huggingface/push_to_hub.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "# Load model and push to Huggingface" 15 | ] 16 | }, 17 | { 18 | "cell_type": "code", 19 | "execution_count": null, 20 | "metadata": {}, 21 | "outputs": [], 22 | "source": [ 23 | "from hf_repo.config import SpeechLLMModelConfig\n", 24 | "from hf_repo.model import SpeechLLMModel\n", 25 | "import torch\n", 26 | "\n", 27 | "conf = SpeechLLMModelConfig()\n", 28 | "model = SpeechLLMModel(conf)" 29 | ] 30 | }, 31 | { 32 | "cell_type": "code", 33 | "execution_count": null, 34 | "metadata": {}, 35 | "outputs": [], 36 | "source": [ 37 | "model.load_state_dict(torch.load('/root/ml-research/multi-modal-llm/repo/paper_exp/checkpoints/pth/torch_model_best_checkpoints.pth')) " 38 | ] 39 | }, 40 | { 41 | "cell_type": "code", 42 | "execution_count": null, 43 | "metadata": {}, 44 | "outputs": [], 45 | "source": [ 46 | "conf.register_for_auto_class()\n", 47 | "model.register_for_auto_class(\"AutoModel\")" 48 | ] 49 | }, 50 | { 51 | "cell_type": "code", 52 | "execution_count": null, 53 | "metadata": {}, 54 | "outputs": [], 55 | "source": [ 56 | "conf.push_to_hub('skit-ai/speechllm-1.5B', commit_message=\"checkpoint update\")\n", 57 | "model.push_to_hub('skit-ai/speechllm-1.5B', commit_message=\"checkpoint update\")" 58 | ] 59 | }, 60 | { 61 | "cell_type": "markdown", 62 | "metadata": {}, 63 | "source": [ 64 | "# Infer after push" 65 | ] 66 | }, 67 | { 68 | "cell_type": "code", 69 | "execution_count": null, 70 | "metadata": {}, 71 | "outputs": [], 72 | "source": [ 73 | "# # Load model directly\n", 74 | "from transformers import AutoModel\n", 75 | "model = AutoModel.from_pretrained(\"skit-ai/speechllm-1.5B\", trust_remote_code=True)" 76 | ] 77 | }, 78 | { 79 | "cell_type": "code", 80 | "execution_count": null, 81 | "metadata": {}, 82 | "outputs": [], 83 | "source": [ 84 | "model = model.to(\"cuda\").eval()" 85 | ] 86 | }, 87 | { 88 | "cell_type": "code", 89 | "execution_count": null, 90 | "metadata": {}, 91 | "outputs": [], 92 | "source": [ 93 | "%%time\n", 94 | "model.generate_meta(\n", 95 | " \"/root/ml-research/multi-modal-llm/datadir/data/LibriSpeech/dev-other/1255/90407/1255-90407-0004.flac\", \n", 96 | " instruction=\"Give me the [SpeechActivity, Transcript, Gender, Age, Accent, Emotion] of the audio.\",\n", 97 | " )" 98 | ] 99 | }, 100 | { 101 | "cell_type": "code", 102 | "execution_count": null, 103 | "metadata": {}, 104 | "outputs": [], 105 | "source": [ 106 | "import torchaudio\n", 107 | "\n", 108 | "audio_tensor, rate = torchaudio.load(\"/root/ml-research/multi-modal-llm/datadir/data/LibriSpeech/dev-other/1255/90407/1255-90407-0004.flac\")\n", 109 | "model.generate_meta(\n", 110 | " audio_tensor=audio_tensor, \n", 111 | " instruction=\"Give me the [SpeechActivity, Transcript, Gender, Age, Accen, Emotion] of the audio.\",\n", 112 | " )" 113 | ] 114 | }, 115 | { 116 | "cell_type": "code", 117 | "execution_count": null, 118 | "metadata": {}, 119 | "outputs": [], 120 | "source": [ 121 | "import IPython\n", 122 | "IPython.display.Audio(\"/root/ml-research/multi-modal-llm/datadir/data/LibriSpeech/dev-other/1255/90407/1255-90407-0004.flac\")" 123 | ] 124 | } 125 | ], 126 | "metadata": { 127 | "kernelspec": { 128 | "display_name": "mm_trainer", 129 | "language": "python", 130 | "name": "python3" 131 | }, 132 | "language_info": { 133 | "codemirror_mode": { 134 | "name": "ipython", 135 | "version": 3 136 | }, 137 | "file_extension": ".py", 138 | "mimetype": "text/x-python", 139 | "name": "python", 140 | "nbconvert_exporter": "python", 141 | "pygments_lexer": "ipython3", 142 | "version": "3.11.3" 143 | } 144 | }, 145 | "nbformat": 4, 146 | "nbformat_minor": 2 147 | } 148 | -------------------------------------------------------------------------------- /huggingface/save_checkpoint.py: -------------------------------------------------------------------------------- 1 | from trainer import SpeechLLMLightning 2 | import os 3 | import torch 4 | 5 | ckpt_path = "best_checkpoint.ckpt" 6 | model = SpeechLLMLightning.load_from_checkpoint(ckpt_path) 7 | model = model.eval() 8 | 9 | # Directory to save the models 10 | save_dir = "checkpoints/pth" 11 | os.makedirs(save_dir, exist_ok=True) 12 | 13 | model.llm_model = model.llm_model.merge_and_unload() 14 | torch.save(model.state_dict(), 'torch_model_best_checkpoints.pth') 15 | print("Models saved successfully.") 16 | -------------------------------------------------------------------------------- /model/__pycache__/connector.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/skit-ai/SpeechLLM/f44d361277ae5e2fa687b39f861f630ca2571318/model/__pycache__/connector.cpython-311.pyc -------------------------------------------------------------------------------- /model/__pycache__/encoder.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/skit-ai/SpeechLLM/f44d361277ae5e2fa687b39f861f630ca2571318/model/__pycache__/encoder.cpython-311.pyc -------------------------------------------------------------------------------- /model/__pycache__/llm.cpython-311.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/skit-ai/SpeechLLM/f44d361277ae5e2fa687b39f861f630ca2571318/model/__pycache__/llm.cpython-311.pyc -------------------------------------------------------------------------------- /model/connector.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | 4 | 5 | def get_connector(name, audio_enc_dim, llm_dim, k): 6 | if name == 'linear-pool': 7 | return LinearPoolConnector(audio_enc_dim, llm_dim, k) 8 | elif name == 'linear': 9 | return LinearConnector(audio_enc_dim, llm_dim, k) 10 | elif name == 'cnn': 11 | return CNNConnector(audio_enc_dim, llm_dim, k) 12 | else: 13 | raise NotImplementedError 14 | 15 | class LinearConnector(nn.Module): 16 | def __init__(self, in_dim, out_dim, k): 17 | super().__init__() 18 | self.layer = nn.Linear(in_dim, out_dim) 19 | self.pool = nn.AvgPool1d(kernel_size=k, stride=k) 20 | 21 | def forward(self, x): 22 | x = self.layer(x) 23 | x = x.transpose(1, 2) 24 | x = self.pool(x) 25 | x = x.transpose(1, 2) 26 | return x 27 | 28 | 29 | class LinearPoolConnector(nn.Module): 30 | def __init__(self, input_dim, output_dim, k): 31 | super(LinearPoolConnector, self).__init__() 32 | self.linear1 = nn.Sequential( 33 | nn.Linear(input_dim, output_dim), 34 | nn.ReLU()) 35 | self.pool = nn.AvgPool1d(kernel_size=k, stride=k) 36 | self.linear2 = nn.Sequential( 37 | nn.Linear(output_dim, output_dim), 38 | nn.ReLU(), 39 | nn.Linear(output_dim, output_dim)) 40 | 41 | def forward(self, x): 42 | # x: [B, T, d] 43 | x = self.linear1(x) # x: [B, T, D] 44 | x = x.transpose(1, 2) # x: [B, D, T] 45 | x = self.pool(x) # x: [B, D, T'] 46 | x = x.transpose(1, 2) # x: [B, T', D] 47 | x = self.linear2(x) 48 | return x 49 | 50 | class CNNConnector(nn.Module): 51 | def __init__(self, in_channels, out_channels, k): 52 | super().__init__() 53 | self.layer = nn.Sequential( 54 | nn.ReLU(), 55 | nn.Conv1d(in_channels, out_channels//2, kernel_size=5, 56 | stride=1, padding=0), 57 | nn.ReLU(), 58 | nn.Conv1d(out_channels//2, out_channels, kernel_size=5, 59 | stride=k, padding=0), 60 | nn.ReLU(), 61 | nn.Conv1d(out_channels, out_channels, kernel_size=5, 62 | stride=1, padding=0), 63 | ) 64 | 65 | def forward(self, x): 66 | return self.layer(x.transpose(1,2)).transpose(1,2) 67 | 68 | 69 | 70 | if __name__ == "__main__": 71 | model = CNNConnector(128, 256) 72 | x = torch.randn(4, 50, 128) 73 | z = model(x) 74 | print(z.shape) -------------------------------------------------------------------------------- /model/encoder.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | from transformers import AutoModel 4 | from speechtokenizer import SpeechTokenizer 5 | 6 | def get_audio_encoder(name, finetune_encoder): 7 | if name == "facebook/hubert-xlarge-ll60k": 8 | return TransformerAudioEnoder(model_name='facebook/hubert-xlarge-ll60k', finetune=finetune_encoder) 9 | elif name == "microsoft/wavlm-large": 10 | return TransformerAudioEnoder(model_name='microsoft/wavlm-large', finetune=finetune_encoder) 11 | elif name == "openai/whisper-small": 12 | return WhisperAudioEncoder(finetune=finetune_encoder) 13 | elif name == 'speech-tokenizer': 14 | return SpeechTokenizerEnoder(finetune=finetune_encoder) 15 | elif name == 'audio-clip': 16 | return AudioCLIPEncoder(finetune=finetune_encoder) 17 | else: 18 | raise NotImplementedError 19 | 20 | class TransformerAudioEnoder(nn.Module): 21 | def __init__(self, model_name='facebook/hubert-xlarge-ll60k', finetune=False): 22 | super().__init__() 23 | self.encoder = AutoModel.from_pretrained(model_name) 24 | for param in self.encoder.parameters(): 25 | param.requires_grad = finetune 26 | 27 | for param in self.encoder.encoder.layers[-15:].parameters(): 28 | param.requires_grad = True 29 | 30 | def forward(self, x): 31 | return self.encoder(x).last_hidden_state 32 | 33 | 34 | if __name__ == "__main__": 35 | model = SpeechTokenizerEnoder() 36 | # print(model) 37 | 38 | x = torch.randn(2, 1, 16000) 39 | z = model(x) 40 | print(z.shape) -------------------------------------------------------------------------------- /model/llm.py: -------------------------------------------------------------------------------- 1 | from transformers import AutoModelForCausalLM, AutoTokenizer 2 | from peft import LoraConfig, get_peft_model, PeftModel 3 | 4 | def get_llm(name, use_lora, lora_r, lora_alpha): 5 | llm_tokenizer = AutoTokenizer.from_pretrained(name) 6 | llm_model = AutoModelForCausalLM.from_pretrained( 7 | name, 8 | trust_remote_code=True, 9 | ) 10 | 11 | if use_lora: 12 | peft_config = LoraConfig( 13 | r=lora_r, 14 | lora_alpha=lora_alpha, 15 | target_modules="all-linear", 16 | lora_dropout=0.05, 17 | task_type="CAUSAL_LM", 18 | ) 19 | 20 | llm_model = get_peft_model(llm_model, peft_config) 21 | llm_model.print_trainable_parameters() 22 | 23 | return llm_tokenizer, llm_model -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | torch==2.0.1 2 | wandb==0.15.3 3 | transformers==4.41.2 4 | torchaudio==2.0.2 5 | tokenizers==0.19.1 6 | pytorch-lightning==1.9.4 7 | peft ==0.9.0 8 | librosa==0.10.1 9 | jiwer==3.0.3 10 | huggingface-hub==0.23.0 11 | datasets==2.2.1 12 | accelerate==0.30.0 13 | streamlit==1.34.0 14 | audio_recorder_streamlit==0.0.8 -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- 1 | from pytorch_lightning import Trainer 2 | from pytorch_lightning.loggers import WandbLogger 3 | from trainer import SpeechLLMLightning 4 | from dataset import InstructionalAudioDataset 5 | 6 | import torch.utils.data as data_utils 7 | from dataset import InstructionalAudioDataset, MyCollator 8 | 9 | if __name__ == "__main__": 10 | 11 | model_config = { 12 | 'audio_enc_dim': 1024, 13 | 'llm_dim': 2048, 14 | 'audio_encoder_name': "microsoft/wavlm-large", #"facebook/hubert-xlarge-ll60k", 15 | 'connector_name': 'cnn', 16 | 'llm_name': "TinyLlama/TinyLlama-1.1B-Chat-v1.0", #"google/gemma-2b-it", #"TinyLlama/TinyLlama-1.1B-Chat-v1.0", #"microsoft/phi-2", 17 | 'finetune_encoder': False, 18 | 'connector_k': 2, 19 | 'use_lora': True, 20 | 'lora_r': 8, 21 | 'lora_alpha': 16, 22 | 'max_lr': 3e-4, 23 | 'total_training_step': 1000000, 24 | 'warmup_steps': 100, 25 | 'train_batch_per_epoch': 10000, 26 | 'grad_accumulate_steps': 8 27 | } 28 | 29 | model = SpeechLLMLightning.load_from_checkpoint("./path-to-checkpoint-dir/best_checkpoint.ckpt") 30 | tokenizer = model.llm_tokenizer 31 | 32 | test_dataset = InstructionalAudioDataset( 33 | csv_file='./path-to-test-dir/librispeech-test-clean.csv', # same train.csv and dev.csv 34 | mode='test' 35 | ) 36 | 37 | my_collator = MyCollator(model_config['audio_encoder_name'], tokenizer) 38 | test_loader = data_utils.DataLoader(test_dataset, batch_size=1, shuffle=False, collate_fn=my_collator, num_workers=3) 39 | 40 | trainer = Trainer( 41 | accelerator='gpu', devices=1 42 | ) 43 | trainer.test(model=model, dataloaders=test_loader) 44 | -------------------------------------------------------------------------------- /train.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | from pytorch_lightning import Trainer 4 | from pytorch_lightning.loggers import WandbLogger 5 | from trainer import SpeechLLMLightning 6 | from dataset import InstructionalAudioDataset, MyCollator 7 | from pytorch_lightning.strategies import DDPStrategy 8 | 9 | import torch.utils.data as data_utils 10 | from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping 11 | import wandb 12 | 13 | if __name__ == "__main__": 14 | log_path = 'WavLM-CNN-tinyllama-run1' 15 | wandb.init(project="mmllm", name=log_path) 16 | logger = WandbLogger(project="mmllm", name=log_path) 17 | 18 | model_config = { 19 | 'audio_enc_dim': 1024, 20 | 'llm_dim': 2048, 21 | 'audio_encoder_name': "microsoft/wavlm-large", 22 | 'connector_name': 'cnn', 23 | 'llm_name': "TinyLlama/TinyLlama-1.1B-Chat-v1.0", 24 | 'finetune_encoder': False, 25 | 'connector_k': 2, 26 | 'use_lora': True, 27 | 'lora_r': 8, 28 | 'lora_alpha': 16, 29 | 'max_lr': 1e-4, 30 | 'total_training_step': 10000000, 31 | 'warmup_steps': 100, 32 | 'train_batch_per_epoch': 10000, 33 | 'grad_accumulate_steps': 8 34 | } 35 | 36 | model = SpeechLLMLightning(**model_config) 37 | tokenizer = model.llm_tokenizer 38 | 39 | train_dataset = InstructionalAudioDataset( 40 | csv_file = './data_samples/train.csv', 41 | mode='train', 42 | random_keys_prob=0.2, 43 | ) 44 | 45 | val_dataset = InstructionalAudioDataset( 46 | csv_file='./data_samples/dev.csv', 47 | mode='test' 48 | ) 49 | 50 | print(len(train_dataset), len(val_dataset)) 51 | 52 | my_collator = MyCollator(model_config['audio_encoder_name'], tokenizer) 53 | train_loader = data_utils.DataLoader(train_dataset, batch_size=1, shuffle=True, collate_fn=my_collator, num_workers=3) 54 | val_loader = data_utils.DataLoader(val_dataset, batch_size=1, shuffle=False, collate_fn=my_collator, num_workers=3) 55 | 56 | checkpoint_callback = ModelCheckpoint(dirpath=f"checkpoints", filename=log_path+'-{epoch}', save_top_k=1, monitor="val/loss", save_last=True) 57 | early_stop_callback = EarlyStopping(monitor="val/loss", min_delta=0.00, patience=10, verbose=False, mode="min") 58 | 59 | trainer = Trainer( 60 | max_epochs=model_config['total_training_step']//model_config['train_batch_per_epoch'], gpus=2, 61 | strategy=DDPStrategy(find_unused_parameters=True), 62 | limit_train_batches=model_config['train_batch_per_epoch'], 63 | limit_val_batches=model_config['train_batch_per_epoch'], 64 | log_every_n_steps=model_config['train_batch_per_epoch'], 65 | enable_checkpointing=True, 66 | callbacks=[checkpoint_callback], 67 | fast_dev_run=False, logger=logger, 68 | accumulate_grad_batches=model_config['grad_accumulate_steps'], 69 | resume_from_checkpoint=None 70 | ) 71 | trainer.fit(model, train_loader, val_loader) 72 | 73 | -------------------------------------------------------------------------------- /trainer.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | from torch.optim import Adam 4 | from torch.optim.lr_scheduler import LambdaLR 5 | 6 | import wandb 7 | import pytorch_lightning as pl 8 | import numpy as np 9 | from jiwer import wer 10 | import torchmetrics 11 | import random 12 | import re 13 | import json 14 | 15 | from model.encoder import get_audio_encoder, TransformerAudioEnoder 16 | from model.connector import get_connector, LinearConnector, LinearPoolConnector, CNNConnector 17 | from model.llm import get_llm 18 | 19 | class SpeechLLMLightning(pl.LightningModule): 20 | def __init__(self, 21 | audio_enc_dim=512, 22 | llm_dim=2048, 23 | audio_encoder_name="speech-tokenizer", 24 | connector_name='linear-pool', 25 | llm_name="TinyLlama/TinyLlama-1.1B-Chat-v1.0", 26 | finetune_encoder=False, 27 | connector_k=5, 28 | use_lora=True, 29 | lora_r=32, 30 | lora_alpha=2, 31 | max_lr=3e-4, 32 | total_training_step=500000, 33 | warmup_steps=1000, 34 | **kwargs 35 | ): 36 | super().__init__() 37 | self.save_hyperparameters() 38 | 39 | self.audio_enc_dim = audio_enc_dim 40 | self.llm_dim = llm_dim 41 | self.llm_name = llm_name 42 | self.finetune_encoder = finetune_encoder 43 | self.use_lora = use_lora 44 | 45 | self.audio_encoder = get_audio_encoder(audio_encoder_name, finetune_encoder) 46 | self.connector = get_connector(connector_name, audio_enc_dim, llm_dim, connector_k) 47 | self.llm_tokenizer, self.llm_model = get_llm(llm_name, use_lora, lora_r, lora_alpha) 48 | 49 | self.max_lr = max_lr 50 | self.total_training_step = total_training_step 51 | self.warmup_steps = warmup_steps 52 | self.use_embedding_loss = False 53 | self.num_validation_samples = 5000 54 | 55 | def configure_optimizers(self): 56 | opt = [ 57 | {"params": self.audio_encoder.parameters(), "lr": 1e-5}, 58 | {"params": self.connector.parameters(), "lr": self.max_lr}, 59 | {"params": self.llm_model.parameters(), "lr": self.max_lr}, 60 | ] 61 | optimizer = Adam(opt, lr=self.max_lr) 62 | return optimizer 63 | 64 | def encode(self, mel, pre_tokenized_ids, post_tokenized_ids, output_tokenized_ids, return_embedding_loss=False): 65 | batch_size = mel.shape[0] 66 | 67 | speech_embeds = self.audio_encoder(mel) 68 | speech_embeds = self.connector(speech_embeds) 69 | 70 | embedder = self.llm_model.model.model.embed_tokens 71 | pre_prompt_embeds = embedder(pre_tokenized_ids) 72 | post_prompt_embeds = embedder(post_tokenized_ids) 73 | output_prompt_embeds = embedder(output_tokenized_ids) 74 | 75 | combined_embeds = torch.cat([pre_prompt_embeds, speech_embeds, post_prompt_embeds, output_prompt_embeds], dim=1) 76 | atts = torch.ones(combined_embeds.size()[:-1], dtype=torch.long).to(combined_embeds.device) 77 | 78 | input_token_length = pre_tokenized_ids.shape[1] + speech_embeds.shape[1] + post_tokenized_ids.shape[1] 79 | label_ids = torch.cat([ 80 | torch.ones([batch_size, input_token_length], device=combined_embeds.device)*-100, 81 | output_tokenized_ids 82 | ], 1).to(combined_embeds.device).to(torch.int64) 83 | return combined_embeds, atts, label_ids 84 | 85 | def forward(self, embeds, atts, label_ids): 86 | out = self.llm_model( 87 | inputs_embeds=embeds, 88 | attention_mask=atts, 89 | labels=label_ids, 90 | ) 91 | return out 92 | 93 | def training_step(self, batch, batch_idx): 94 | mel, pre_tokenized_ids, post_tokenized_ids, output_tokenized_ids = batch 95 | embeds, atts, label_ids = self.encode(mel, pre_tokenized_ids, post_tokenized_ids, output_tokenized_ids) 96 | outputs = self.forward(embeds, atts, label_ids) 97 | loss = outputs["loss"] 98 | self.log("train/loss", loss, on_epoch=False) 99 | return loss 100 | 101 | def validation_step(self, batch, batch_idx): 102 | mel, pre_tokenized_ids, post_tokenized_ids, output_tokenized_ids = batch 103 | embeds, atts, label_ids = self.encode(mel, pre_tokenized_ids, post_tokenized_ids, output_tokenized_ids) 104 | outputs = self.forward(embeds, atts, label_ids) 105 | loss = outputs["loss"] 106 | self.log("val/loss", loss, on_step=False, on_epoch=True, prog_bar=True, logger=True) 107 | 108 | logits = outputs.logits 109 | predicted_ids = torch.argmax(logits, dim=-1).cpu() 110 | 111 | generated_output_text = self.llm_tokenizer.decode(predicted_ids[0], skip_special_tokens=False) 112 | target_text = self.llm_tokenizer.decode(output_tokenized_ids[0], skip_special_tokens=False) 113 | 114 | extracted_pred = self.extract_prediction_values(generated_output_text) 115 | extracted_target = self.extract_prediction_values(target_text) 116 | 117 | keys = extracted_target.keys() 118 | pred_keys = extracted_pred.keys() 119 | 120 | for key in keys: 121 | if key not in pred_keys: 122 | extracted_pred[key] = "NA" 123 | 124 | if 'Transcript' in keys: 125 | target_transcript = extracted_target['Transcript'] 126 | predicted_transcript = extracted_pred['Transcript'] 127 | wer_metric = wer(target_transcript.lower(), predicted_transcript.lower()) 128 | self.log("val/wer", wer_metric, on_step=False, on_epoch=True, prog_bar=True, logger=True) 129 | 130 | if 'Response' in keys: 131 | target_transcript = extracted_target['Response'] 132 | predicted_transcript = extracted_pred['Response'] 133 | wer_metric = wer(target_transcript.lower(), predicted_transcript.lower()) 134 | self.log("val/response_wer", wer_metric, on_step=False, on_epoch=True, prog_bar=True, logger=True) 135 | 136 | if 'SpeechActivity' in keys: 137 | target_isspeech = extracted_target['SpeechActivity'] 138 | predicted_isspeech = extracted_pred['SpeechActivity'] 139 | self.log("val/speech_activity", float(target_isspeech.lower()==predicted_isspeech.lower()), on_step=False, on_epoch=True, prog_bar=True, logger=True) 140 | 141 | if 'Gender' in keys: 142 | target_gender = extracted_target['Gender'] 143 | predicted_gender = extracted_pred['Gender'] 144 | self.log("val/gender", float(target_gender.lower()==predicted_gender.lower()), on_step=False, on_epoch=True, prog_bar=True, logger=True) 145 | 146 | if 'Emotion' in keys: 147 | target_emotion = extracted_target['Emotion'] 148 | predicted_emotion = extracted_pred['Emotion'] 149 | self.log("val/emotion", float(target_emotion.lower()==predicted_emotion.lower()), on_step=False, on_epoch=True, prog_bar=True, logger=True) 150 | 151 | if 'Age' in keys: 152 | target_age = extracted_target['Age'] 153 | predicted_age = extracted_pred['Age'] 154 | self.log("val/age", float(target_age.lower()==predicted_age.lower()), on_step=False, on_epoch=True, prog_bar=True, logger=True) 155 | 156 | if 'Accent' in keys: 157 | target_accent = extracted_target['Accent'] 158 | predicted_accent = extracted_pred['Accent'] 159 | self.log("val/accent", float(target_accent.lower()==predicted_accent.lower()), on_step=False, on_epoch=True, prog_bar=True, logger=True) 160 | 161 | if batch_idx in self.selected_samples_for_logging: 162 | sample_idx = self.selected_samples_for_logging.index(batch_idx) 163 | # Use wandb.log to log prediction and truth texts 164 | wandb.log({ 165 | f"val_sample_{sample_idx}_pred": wandb.Html(f"
{str(extracted_pred)}
"), 166 | f"val_sample_{sample_idx}_target": wandb.Html(f"
{str(target_text).replace('', '').replace('', '')}
"), 167 | f"val_sample_{sample_idx}_gen": wandb.Html(f"
{generated_output_text.replace('', '').replace('', '')}
"), 168 | }, commit=False) 169 | 170 | return {"val_loss": loss} 171 | 172 | def test_step(self, batch, batch_idx): 173 | mel, pre_tokenized_ids, post_tokenized_ids, output_tokenized_ids = batch 174 | embeds, atts, label_ids = self.encode(mel, pre_tokenized_ids, post_tokenized_ids, output_tokenized_ids) 175 | outputs = self.forward(embeds, atts, label_ids) 176 | loss = outputs["loss"] 177 | self.log("val/loss", loss, on_step=False, on_epoch=True, prog_bar=True, logger=True) 178 | 179 | logits = outputs.logits 180 | predicted_ids = torch.argmax(logits, dim=-1) 181 | 182 | input_token_length = output_tokenized_ids.shape[1] 183 | generated_output_text = self.llm_tokenizer.decode(predicted_ids[0], skip_special_tokens=False) 184 | target_text = self.llm_tokenizer.decode(output_tokenized_ids[0], skip_special_tokens=False) 185 | 186 | extracted_pred = self.extract_prediction_values(generated_output_text) 187 | extracted_target = self.extract_prediction_values(target_text) 188 | 189 | keys = extracted_target.keys() 190 | pred_keys = extracted_pred.keys() 191 | 192 | for key in keys: 193 | if key not in pred_keys: 194 | extracted_pred[key] = "NA" 195 | 196 | if 'Transcript' in keys: 197 | target_transcript = extracted_target['Transcript'] 198 | predicted_transcript = extracted_pred['Transcript'] 199 | wer_metric = wer(target_transcript.lower(), predicted_transcript.lower()) 200 | self.log("val/wer", wer_metric, on_step=False, on_epoch=True, prog_bar=True, logger=True) 201 | 202 | if 'Response' in keys: 203 | target_transcript = extracted_target['Response'] 204 | predicted_transcript = extracted_pred['Response'] 205 | wer_metric = wer(target_transcript.lower(), predicted_transcript.lower()) 206 | self.log("val/response_wer", wer_metric, on_step=False, on_epoch=True, prog_bar=True, logger=True) 207 | 208 | if 'SpeechActivity' in keys: 209 | target_isspeech = extracted_target['SpeechActivity'] 210 | predicted_isspeech = extracted_pred['SpeechActivity'] 211 | self.log("val/speech_activity", float(target_isspeech.lower()==predicted_isspeech.lower()), on_step=False, on_epoch=True, prog_bar=True, logger=True) 212 | 213 | if 'Gender' in keys: 214 | target_gender = extracted_target['Gender'] 215 | predicted_gender = extracted_pred['Gender'] 216 | self.log("val/gender", float(target_gender.lower()==predicted_gender.lower()), on_step=False, on_epoch=True, prog_bar=True, logger=True) 217 | 218 | if 'Emotion' in keys: 219 | target_emotion = extracted_target['Emotion'] 220 | predicted_emotion = extracted_pred['Emotion'] 221 | self.log("val/emotion", float(target_emotion.lower()==predicted_emotion.lower()), on_step=False, on_epoch=True, prog_bar=True, logger=True) 222 | 223 | if 'Age' in keys: 224 | target_age = extracted_target['Age'] 225 | predicted_age = extracted_pred['Age'] 226 | self.log("val/age", float(target_age.lower()==predicted_age.lower()), on_step=False, on_epoch=True, prog_bar=True, logger=True) 227 | 228 | if 'Accent' in keys: 229 | target_accent = extracted_target['Accent'] 230 | predicted_accent = extracted_pred['Accent'] 231 | self.log("val/accent", float(target_accent.lower()==predicted_accent.lower()), on_step=False, on_epoch=True, prog_bar=True, logger=True) 232 | 233 | return {"val_loss": loss} 234 | 235 | def on_validation_epoch_start(self): 236 | """Select two random validation samples to log for each epoch.""" 237 | self.selected_samples_for_logging = random.sample(range(self.num_validation_samples), 2) 238 | 239 | 240 | def extract_dictionary(self, input_string): 241 | pattern = r'\s*(\{.*?\})\s*' 242 | match = re.search(pattern, input_string, re.DOTALL) 243 | if match: 244 | dict_string = match.group(1) 245 | dict_string = re.sub(r',\s*}', '}', dict_string) 246 | try: 247 | return json.loads(dict_string) 248 | except json.JSONDecodeError as e: 249 | return {} 250 | else: 251 | return {} 252 | 253 | def extract_prediction_values(self, input_string): 254 | json_str_match = re.search(r'\s*\{.*?\}\s*', input_string) 255 | try: 256 | json_str = json_str_match.group(0) 257 | except: 258 | json_str = '{}' 259 | return self.extract_dictionary(json_str) --------------------------------------------------------------------------------