multimodalart HF Staff commited on
Commit
4857f4f
Β·
verified Β·
1 Parent(s): 105aec6

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +36 -43
app.py CHANGED
@@ -20,15 +20,18 @@ torch.load = _patched_torch_load
20
  import sys
21
  sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
22
 
23
- import lightning as L
24
  import numpy as np
25
  import gradio as gr
26
  import whisper
27
  import tempfile
28
  import time
 
 
29
  from transformers import AutoConfig
30
  from transformers.models.qwen2_5_omni.modeling_qwen2_5_omni import Qwen2_5OmniAudioEncoder
31
  from huggingface_hub import snapshot_download
 
32
 
33
  from src.audiointeraction.dataset.TOKENS import (
34
  ASSISTANT, AUDIO_BEGIN, ENGLISH, KEEP_SILENCE, ONLINE, PAD,
@@ -40,11 +43,6 @@ from src.audiointeraction.generate.base import (
40
  )
41
  from src.audiointeraction.model import GPT, Config
42
  from src.audiointeraction.tokenizer import Tokenizer
43
- from src.audiointeraction.utils import get_default_supported_precision
44
-
45
- from safetensors.torch import load_file
46
- from pathlib import Path
47
- import json
48
 
49
  # ── Constants ──────────────────────────────────────────────
50
 
@@ -64,6 +62,15 @@ EMOTION_EMOJI = {
64
  }
65
 
66
 
 
 
 
 
 
 
 
 
 
67
  # ── Model loading (module scope, eager) ────────────────────
68
 
69
  def _resolve_checkpoint_paths(checkpoint_dir: str):
@@ -76,32 +83,6 @@ def _resolve_checkpoint_paths(checkpoint_dir: str):
76
  )
77
 
78
 
79
- def _load_model(fabric, model_config_dir, trained_checkpoint):
80
- """Load GPT from sharded safetensors using Lightning Fabric."""
81
- config = Config.from_file(Path(model_config_dir) / "model_config.yaml")
82
- with fabric.init_module(empty_init=True):
83
- model = GPT(config)
84
- model = fabric.setup(model)
85
-
86
- checkpoint_dir = Path(trained_checkpoint)
87
- index_path = checkpoint_dir / "model.safetensors.index.json"
88
- if not index_path.is_file():
89
- raise FileNotFoundError(f"No model.safetensors.index.json under {checkpoint_dir}")
90
-
91
- with open(index_path) as f:
92
- index = json.load(f)
93
- shard_files = sorted(set(index["weight_map"].values()))
94
-
95
- state_dict = {}
96
- for shard in shard_files:
97
- state_dict.update(load_file(str(checkpoint_dir / shard), device="cpu"))
98
-
99
- missing, unexpected = model.load_state_dict(state_dict, strict=True)
100
- if missing or unexpected:
101
- print(f"[load_model] missing={missing[:3]}… unexpected={unexpected[:3]}…")
102
- return model
103
-
104
-
105
  def _load_audio_encoder(qwen_omni_ckpt, audio_tower_ckpt, device):
106
  cfg = AutoConfig.from_pretrained(qwen_omni_ckpt)
107
  audio_cfg = cfg.thinker_config.audio_config
@@ -125,15 +106,28 @@ print(f"Model downloaded to {ckpt_dir}")
125
  model_config_dir, trained_checkpoint, qwen_omni_ckpt, audio_tower_ckpt = \
126
  _resolve_checkpoint_paths(ckpt_dir)
127
 
128
- set_seed_called = False
129
- # Use Lightning Fabric for proper precision and device management
130
  device = "cuda"
131
- precision = get_default_supported_precision(training=False)
132
- fabric = L.Fabric(devices=1, precision=precision)
133
 
134
  print("Loading language model...")
135
- model = _load_model(fabric, model_config_dir, trained_checkpoint)
136
- model = fabric.setup(model)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
  model.eval()
138
 
139
  print("Loading audio encoder...")
@@ -250,11 +244,11 @@ def interact(audio_file, text_instruction=""):
250
  if int_token == TEXT_BEGIN:
251
  listening = False
252
  current_text = [int_token]
253
- print(f"[interact] TEXT_BEGIN at chunk {audio_idx}/{n_chunks}")
254
  elif int_token == KEEP_SILENCE:
255
- print(f"[interact] KEEP_SILENCE at chunk {audio_idx}/{n_chunks}")
256
  else:
257
- print(f"[interact] Unexpected token {int_token} at chunk {audio_idx}/{n_chunks}")
258
  break
259
  else:
260
  current_text.append(int_token)
@@ -278,7 +272,7 @@ def interact(audio_file, text_instruction=""):
278
  # Handle any incomplete turn
279
  if not listening and len(current_text) > 1:
280
  text_tokens = current_text[1:] # skip TEXT_BEGIN
281
- if text_tokens[0] in EMOTION_EMOJI if text_tokens else False:
282
  emotion_tag = EMOTION_EMOJI[text_tokens[0]]
283
  text_tokens = text_tokens[1:]
284
  decoded = tokenizer.decode(torch.tensor(text_tokens))
@@ -312,7 +306,6 @@ def interact(audio_file, text_instruction=""):
312
 
313
  CSS = """
314
  #col-container { max-width: 900px; margin: 0 auto; }
315
- .dark .gradio-container { color: var(--body-text-color); }
316
  """
317
 
318
  with gr.Blocks(theme=gr.themes.Citrus(), css=CSS) as demo:
 
20
  import sys
21
  sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
22
 
23
+ import random
24
  import numpy as np
25
  import gradio as gr
26
  import whisper
27
  import tempfile
28
  import time
29
+ import json
30
+ from pathlib import Path
31
  from transformers import AutoConfig
32
  from transformers.models.qwen2_5_omni.modeling_qwen2_5_omni import Qwen2_5OmniAudioEncoder
33
  from huggingface_hub import snapshot_download
34
+ from safetensors.torch import load_file
35
 
36
  from src.audiointeraction.dataset.TOKENS import (
37
  ASSISTANT, AUDIO_BEGIN, ENGLISH, KEEP_SILENCE, ONLINE, PAD,
 
43
  )
44
  from src.audiointeraction.model import GPT, Config
45
  from src.audiointeraction.tokenizer import Tokenizer
 
 
 
 
 
46
 
47
  # ── Constants ──────────────────────────────────────────────
48
 
 
62
  }
63
 
64
 
65
+ def set_seed(seed: int = 1337) -> None:
66
+ random.seed(seed)
67
+ np.random.seed(seed)
68
+ torch.manual_seed(seed)
69
+ torch.cuda.manual_seed_all(seed)
70
+ torch.backends.cudnn.deterministic = True
71
+ torch.backends.cudnn.benchmark = False
72
+
73
+
74
  # ── Model loading (module scope, eager) ────────────────────
75
 
76
  def _resolve_checkpoint_paths(checkpoint_dir: str):
 
83
  )
84
 
85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  def _load_audio_encoder(qwen_omni_ckpt, audio_tower_ckpt, device):
87
  cfg = AutoConfig.from_pretrained(qwen_omni_ckpt)
88
  audio_cfg = cfg.thinker_config.audio_config
 
106
  model_config_dir, trained_checkpoint, qwen_omni_ckpt, audio_tower_ckpt = \
107
  _resolve_checkpoint_paths(ckpt_dir)
108
 
109
+ set_seed(1337)
 
110
  device = "cuda"
 
 
111
 
112
  print("Loading language model...")
113
+ config = Config.from_file(Path(model_config_dir) / "model_config.yaml")
114
+ model = GPT(config)
115
+ model.max_seq_length = config.block_size
116
+
117
+ checkpoint_dir = Path(trained_checkpoint)
118
+ index_path = checkpoint_dir / "model.safetensors.index.json"
119
+ with open(index_path) as f:
120
+ index = json.load(f)
121
+ shard_files = sorted(set(index["weight_map"].values()))
122
+ state_dict = {}
123
+ for shard in shard_files:
124
+ state_dict.update(load_file(str(checkpoint_dir / shard), device="cpu"))
125
+ missing, unexpected = model.load_state_dict(state_dict, strict=True)
126
+ if missing or unexpected:
127
+ print(f"[load_model] missing={missing[:3]}… unexpected={unexpected[:3]}…")
128
+ del state_dict # free memory
129
+
130
+ model = model.to(device).to(torch.bfloat16)
131
  model.eval()
132
 
133
  print("Loading audio encoder...")
 
244
  if int_token == TEXT_BEGIN:
245
  listening = False
246
  current_text = [int_token]
247
+ print(f"[interact] TEXT_BEGIN at chunk {audio_idx}/{n_chunks}", flush=True)
248
  elif int_token == KEEP_SILENCE:
249
+ print(f"[interact] KEEP_SILENCE at chunk {audio_idx}/{n_chunks}", flush=True)
250
  else:
251
+ print(f"[interact] Unexpected token {int_token} at chunk {audio_idx}/{n_chunks}", flush=True)
252
  break
253
  else:
254
  current_text.append(int_token)
 
272
  # Handle any incomplete turn
273
  if not listening and len(current_text) > 1:
274
  text_tokens = current_text[1:] # skip TEXT_BEGIN
275
+ if text_tokens and text_tokens[0] in EMOTION_EMOJI:
276
  emotion_tag = EMOTION_EMOJI[text_tokens[0]]
277
  text_tokens = text_tokens[1:]
278
  decoded = tokenizer.decode(torch.tensor(text_tokens))
 
306
 
307
  CSS = """
308
  #col-container { max-width: 900px; margin: 0 auto; }
 
309
  """
310
 
311
  with gr.Blocks(theme=gr.themes.Citrus(), css=CSS) as demo: