import argparse import torch import os import json from tqdm import tqdm import shortuuid import whisper from omni_speech.constants import SPEECH_TOKEN_INDEX, DEFAULT_SPEECH_TOKEN, IGNORE_INDEX from omni_speech.conversation import conv_templates, SeparatorStyle from omni_speech.model.builder import load_pretrained_model, load_pretrained_model_asr from omni_speech.utils import disable_torch_init from omni_speech.datasets.preprocess import tokenizer_speech_token from torch.utils.data import Dataset, DataLoader import transformers from typing import Dict, Optional, Sequence, List import math import re def split_list(lst, n): """Split a list into n (roughly) equal-sized chunks""" chunk_size = math.ceil(len(lst) / n) # integer division return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)] def get_chunk(lst, n, k): chunks = split_list(lst, n) return chunks[k] def preprocess_qwen(sources, tokenizer: transformers.PreTrainedTokenizer, has_speech: bool = False, max_len=2048, system_message: str = "You are a helpful language and speech assistant. You are able to understand the speech content that the user provides, and assist the user with a variety of tasks using natural language.", tools = None) -> Dict: roles = {"human": "<|im_start|>user", "gpt": "<|im_start|>assistant"} unmask_tokens = ["<|im_start|>", "<|im_end|>"] unmask_tokens_idx = [tokenizer.convert_tokens_to_ids(x) for x in unmask_tokens] im_start = unmask_tokens_idx[0] im_end = unmask_tokens_idx[1] nl_tokens = tokenizer("\n").input_ids speech_token_index = tokenizer.convert_tokens_to_ids("\n") _system = tokenizer("system").input_ids + nl_tokens _user = tokenizer("user").input_ids + nl_tokens _assistant = tokenizer("assistant").input_ids + nl_tokens # Apply prompt templates input_ids, targets = [], [] source = sources if roles[source[0]["from"]] != roles["human"]: source = source[1:] input_id, target = [], [] if tools is not None: dict_sys = { "role": "system", "content": system_message } system = tokenizer.apply_chat_template([dict_sys], tools = tools) else: system = [im_start] + _system + tokenizer(system_message).input_ids + [im_end] + nl_tokens input_id += system target += [im_start] + [IGNORE_INDEX] * (len(system) - 3) + [im_end] + nl_tokens assert len(input_id) == len(target) for j, sentence in enumerate(source): role = roles[sentence["from"]] if has_speech and sentence["value"] is not None and "" in sentence["value"]: num_speech = len(re.findall(DEFAULT_SPEECH_TOKEN, sentence["value"])) texts = sentence["value"].split('') _input_id = tokenizer(role).input_ids + nl_tokens for i,text in enumerate(texts): _input_id += tokenizer(text).input_ids if iuser": _target = [im_start] + [IGNORE_INDEX] * (len(_input_id) - 3) + [im_end] + nl_tokens elif role == "<|im_start|>assistant": _target = [im_start] + [IGNORE_INDEX] * len(tokenizer(role).input_ids) + _input_id[len(tokenizer(role).input_ids) + 1 : -2] + [im_end] + nl_tokens else: raise NotImplementedError target += _target input_ids.append(input_id) targets.append(target) input_ids = torch.tensor(input_ids, dtype=torch.long) targets = torch.tensor(targets, dtype=torch.long) return input_ids def ctc_postprocess(tokens, blank): _toks = tokens.squeeze(0).tolist() deduplicated_toks = [v for i, v in enumerate(_toks) if i == 0 or v != _toks[i - 1]] hyp = [v for v in deduplicated_toks if v != blank] hyp = " ".join(list(map(str, hyp))) return hyp def process_speech(speech_file, input_type, speech_normalize): speech = whisper.load_audio(speech_file) if input_type == "raw": speech = torch.from_numpy(speech) if speech_normalize: speech = torch.nn.functional.layer_norm(speech, speech.shape) elif input_type == "mel": speech = whisper.pad_or_trim(speech) speech = whisper.log_mel_spectrogram(speech, n_mels=args.mel_size).permute(1, 0) speech_lengths = torch.LongTensor([speech.shape[0]]) return speech, speech_lengths def eval_model(args): # Model disable_torch_init() # model_path = os.path.expanduser(args.model_path) tokenizer, model, context_len = load_pretrained_model(args.model_path, args.model_base, is_lora=args.is_lora, s2s=args.s2s) questions = json.load(open(os.path.expanduser(args.question_file), "r")) questions = get_chunk(questions, args.num_chunks, args.chunk_idx) answers_file = os.path.expanduser(args.answer_file) os.makedirs(os.path.dirname(answers_file), exist_ok=True) ans_list = [] for line in tqdm(questions): answer = None idx = line["id"] try: gt = line["conversations"][1]["value"] except: gt = None speech_files = line["speech"] qs = line["conversations"][0]["value"] cur_prompt = qs if "tools" in line: tools = line["tools"] json_objects = tools.split("\n\n") if len(json_objects) > 1: json_objects = json_objects[:-1] fc = [json.loads(obj) for obj in json_objects] else: fc = None conv = conv_templates[args.conv_mode].copy() conv.append_message(conv.roles[0], qs) conv.append_message(conv.roles[1], None) prompt = conv.get_prompt(tokenizer, args.system_prompt) input_ids = preprocess_qwen([line["conversations"][0],{'from': 'gpt','value': None}], tokenizer, has_speech=True, tools = fc).cuda() speech_num = list(input_ids.squeeze()).count(SPEECH_TOKEN_INDEX) try: speechs = [process_speech(f, args.input_type, model.config.speech_normalize) for f in speech_files] except: speechs = [process_speech(speech_files, args.input_type, model.config.speech_normalize)] speech_tensor = [] for item in speechs: speech_tensor.append(item[0]) speech_length = [] for item in speechs: speech_length.append(item[1]) speech_tensor = [tensor.to(dtype=torch.float16, device='cuda', non_blocking=True) for tensor in speech_tensor] speech_length = [tensor.to(device='cuda', non_blocking=True) for tensor in speech_length] with torch.inference_mode(): if args.s2s: outputs = model.generate( input_ids, speech=speech_tensor[:speech_num], speech_lengths=speech_length[:speech_num], do_sample=True if args.temperature > 0 else False, temperature=args.temperature, top_p=args.top_p, num_beams=args.num_beams, max_new_tokens=args.max_new_tokens, use_cache=True, streaming_unit_gen=False, ) output_ids, output_units = outputs else: outputs = model.generate( input_ids, speech=speech_tensor[:speech_num], speech_lengths=speech_length[:speech_num], do_sample=True if args.temperature > 0 else False, temperature=args.temperature, top_p=args.top_p, num_beams=args.num_beams, max_new_tokens=args.max_new_tokens, use_cache=True, ) output_ids = outputs outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip() if args.s2s: output_units = ctc_postprocess(output_units, blank=model.config.unit_vocab_size) if args.s2s: print(f"U-{idx}\t{output_units}") if args.s2s: ans_list.append({"question_id": idx, "prediction": outputs, "prediction_units": output_units, "answer": answer}) # ans_file.write(json.dumps({"question_id": idx, "prediction": outputs, "prediction_units": output_units, "answer": answer}, indent=2) + "\n") else: ans_list.append({"question_id": idx, "prediction": outputs, "answer": answer}) # ans_file.write(json.dumps({"question_id": idx, "prediction": outputs, "answer": answer}, indent=2) + "\n") if len(line["conversations"]) > 2: for i in range(2, len(line["conversations"]), 2): input_ids = torch.cat((input_ids, output_ids), dim=1) gt = line["conversations"][i + 1]["value"] qs = line["conversations"][i]["value"] cur_prompt = qs conv = conv_templates[args.conv_mode].copy() conv.append_message(conv.roles[0], qs) conv.append_message(conv.roles[1], None) prompt = conv.get_prompt(tokenizer, args.system_prompt) input_ids_new = preprocess_qwen([line["conversations"][i],{'from': 'gpt','value': None}], tokenizer, has_speech=True, tools = fc).cuda() input_ids = torch.cat((input_ids, input_ids_new), dim=1) speech_num = list(input_ids.squeeze()).count(SPEECH_TOKEN_INDEX) with torch.inference_mode(): if args.s2s: outputs = model.generate( input_ids, speech=speech_tensor[:speech_num], speech_lengths=speech_length[:speech_num], do_sample=True if args.temperature > 0 else False, temperature=args.temperature, top_p=args.top_p, num_beams=args.num_beams, max_new_tokens=args.max_new_tokens, use_cache=True, streaming_unit_gen=False, ) output_ids, output_units = outputs else: outputs = model.generate( input_ids, speech=speech_tensor[:speech_num], speech_lengths=speech_length[:speech_num], do_sample=True if args.temperature > 0 else False, temperature=args.temperature, top_p=args.top_p, num_beams=args.num_beams, max_new_tokens=args.max_new_tokens, use_cache=True, ) output_ids = outputs outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip() if args.s2s: output_units = ctc_postprocess(output_units, blank=model.config.unit_vocab_size) if args.s2s: print(f"U-{idx}\t{output_units}") if args.s2s: ans_list.append({"question_id": idx, "prediction": outputs, "prediction_units": output_units, "answer": answer}) # ans_file.write(json.dumps({"question_id": idx, "prediction": outputs, "prediction_units": output_units, "answer": answer}, indent=2) + "\n") else: ans_list.append({"question_id": idx, "prediction": outputs, "answer": answer}) # ans_file.write(json.dumps({"question_id": idx, "prediction": outputs, "answer": answer}, indent=2) + "\n") with open(answers_file, 'w', encoding='utf-8') as f: json.dump(ans_list, f, ensure_ascii=False, indent=2) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--model-path", type=str, default="facebook/opt-350m") parser.add_argument("--model-base", type=str, default=None) parser.add_argument("--question-file", type=str) parser.add_argument("--answer-file", type=str) parser.add_argument("--conv-mode", type=str, default="v1") parser.add_argument("--num-chunks", type=int, default=1) parser.add_argument("--chunk-idx", type=int, default=0) parser.add_argument("--temperature", type=float, default=0) parser.add_argument("--top_p", type=float, default=None) parser.add_argument("--num_beams", type=int, default=1) parser.add_argument("--max_new_tokens", type=int, default=256) parser.add_argument("--input_type", type=str, default="raw") parser.add_argument("--mel_size", type=int, default=128) parser.add_argument("--s2s", action="store_true", default=False) parser.add_argument("--is_lora", action="store_true", default=False) parser.add_argument("--system-prompt", type=str, default=None) args = parser.parse_args() eval_model(args)