|
| 1 | +import re |
| 2 | +import time |
| 3 | +import pickle |
| 4 | +import numpy as np |
| 5 | + |
| 6 | +from edit_distance import SequenceMatcher |
| 7 | +import torch |
| 8 | +from dataset import SpeechDataset |
| 9 | + |
| 10 | +import matplotlib.pyplot as plt |
| 11 | + |
| 12 | + |
| 13 | +from nnDecoderModel import getDatasetLoaders |
| 14 | +from nnDecoderModel import loadModel |
| 15 | +import neuralDecoder.utils.lmDecoderUtils as lmDecoderUtils |
| 16 | +import pickle |
| 17 | +import argparse |
| 18 | + |
| 19 | +parser = argparse.ArgumentParser(description="") |
| 20 | +parser.add_argument("--modelPath", type=str, default=None, help="Path to model") |
| 21 | +input_args = parser.parse_args() |
| 22 | + |
| 23 | + |
| 24 | +with open(input_args.modelPath + "/args", "rb") as handle: |
| 25 | + args = pickle.load(handle) |
| 26 | + |
| 27 | +args["datasetPath"] = "/oak/stanford/groups/henderj/stfan/data/ptDecoder_ctc" |
| 28 | +trainLoaders, testLoaders, loadedData = getDatasetLoaders( |
| 29 | + args["datasetPath"], args["seqLen"], args["maxTimeSeriesLen"], args["batchSize"] |
| 30 | +) |
| 31 | + |
| 32 | +model = loadModel(input_args.modelPath, device="cpu") |
| 33 | + |
| 34 | +device = "cpu" |
| 35 | + |
| 36 | +model.eval() |
| 37 | + |
| 38 | +rnn_outputs = { |
| 39 | + "logits": [], |
| 40 | + "logitLengths": [], |
| 41 | + "trueSeqs": [], |
| 42 | + "transcriptions": [], |
| 43 | +} |
| 44 | +partition = "competition" |
| 45 | +for i, testDayIdx in enumerate([4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 18, 19, 20]): |
| 46 | + # for i, testDayIdx in enumerate(range(len(loadedData[partition]))): |
| 47 | + test_ds = SpeechDataset([loadedData[partition][i]]) |
| 48 | + test_loader = torch.utils.data.DataLoader( |
| 49 | + test_ds, batch_size=1, shuffle=False, num_workers=0 |
| 50 | + ) |
| 51 | + for j, (X, y, X_len, y_len, _) in enumerate(test_loader): |
| 52 | + X, y, X_len, y_len, dayIdx = ( |
| 53 | + X.to(device), |
| 54 | + y.to(device), |
| 55 | + X_len.to(device), |
| 56 | + y_len.to(device), |
| 57 | + torch.tensor([testDayIdx], dtype=torch.int64).to(device), |
| 58 | + ) |
| 59 | + pred = model.forward(X, dayIdx) |
| 60 | + adjustedLens = ((X_len - model.kernelLen) / model.strideLen).to(torch.int32) |
| 61 | + |
| 62 | + for iterIdx in range(pred.shape[0]): |
| 63 | + trueSeq = np.array(y[iterIdx][0 : y_len[iterIdx]].cpu().detach()) |
| 64 | + |
| 65 | + rnn_outputs["logits"].append(pred[iterIdx].cpu().detach().numpy()) |
| 66 | + rnn_outputs["logitLengths"].append( |
| 67 | + adjustedLens[iterIdx].cpu().detach().item() |
| 68 | + ) |
| 69 | + rnn_outputs["trueSeqs"].append(trueSeq) |
| 70 | + |
| 71 | + transcript = loadedData[partition][i]["transcriptions"][j].strip() |
| 72 | + transcript = re.sub(r"[^a-zA-Z\- \']", "", transcript) |
| 73 | + transcript = transcript.replace("--", "").lower() |
| 74 | + rnn_outputs["transcriptions"].append(transcript) |
| 75 | + |
| 76 | + |
| 77 | +MODEL_CACHE_DIR = "/scratch/users/stfan/huggingface" |
| 78 | +# Load OPT 6B model |
| 79 | +llm, llm_tokenizer = lmDecoderUtils.build_opt( |
| 80 | + cacheDir=MODEL_CACHE_DIR, device="auto", load_in_8bit=True |
| 81 | +) |
| 82 | + |
| 83 | +lmDir = "/oak/stanford/groups/henderj/stfan/code/nptlrig2/LanguageModelDecoder/examples/speech/s0/lm_order_exp/5gram/data/lang_test" |
| 84 | +ngramDecoder = lmDecoderUtils.build_lm_decoder( |
| 85 | + lmDir, acoustic_scale=0.5, nbest=100, beam=18 |
| 86 | +) |
| 87 | + |
| 88 | + |
| 89 | + |
| 90 | +# LM decoding hyperparameters |
| 91 | +acoustic_scale = 0.5 |
| 92 | +blank_penalty = np.log(7) |
| 93 | +llm_weight = 0.5 |
| 94 | + |
| 95 | +llm_outputs = [] |
| 96 | +# Generate nbest outputs from 5gram LM |
| 97 | +start_t = time.time() |
| 98 | +nbest_outputs = [] |
| 99 | +for j in range(len(rnn_outputs["logits"])): |
| 100 | + logits = rnn_outputs["logits"][j] |
| 101 | + logits = np.concatenate( |
| 102 | + [logits[:, 1:], logits[:, 0:1]], axis=-1 |
| 103 | + ) # Blank is last token |
| 104 | + logits = lmDecoderUtils.rearrange_speech_logits(logits[None, :, :], has_sil=True) |
| 105 | + nbest = lmDecoderUtils.lm_decode( |
| 106 | + ngramDecoder, |
| 107 | + logits[0], |
| 108 | + blankPenalty=blank_penalty, |
| 109 | + returnNBest=True, |
| 110 | + rescore=True, |
| 111 | + ) |
| 112 | + nbest_outputs.append(nbest) |
| 113 | +time_per_sample = (time.time() - start_t) / len(rnn_outputs["logits"]) |
| 114 | +print(f"5gram decoding took {time_per_sample} seconds per sample") |
| 115 | + |
| 116 | +for i in range(len(rnn_outputs["transcriptions"])): |
| 117 | + new_trans = [ord(c) for c in rnn_outputs["transcriptions"][i]] + [0] |
| 118 | + rnn_outputs["transcriptions"][i] = np.array(new_trans) |
| 119 | + |
| 120 | +# Rescore nbest outputs with LLM |
| 121 | +start_t = time.time() |
| 122 | +llm_out = lmDecoderUtils.cer_with_gpt2_decoder( |
| 123 | + llm, |
| 124 | + llm_tokenizer, |
| 125 | + nbest_outputs[:], |
| 126 | + acoustic_scale, |
| 127 | + rnn_outputs, |
| 128 | + outputType="speech_sil", |
| 129 | + returnCI=True, |
| 130 | + lengthPenalty=0, |
| 131 | + alpha=llm_weight, |
| 132 | +) |
| 133 | +# time_per_sample = (time.time() - start_t) / len(logits) |
| 134 | +print(f"LLM decoding took {time_per_sample} seconds per sample") |
| 135 | + |
| 136 | +print(llm_out["cer"], llm_out["wer"]) |
| 137 | +with open(input_args.modelPath + "/llm_out", "wb") as handle: |
| 138 | + pickle.dump(llm_out, handle) |
| 139 | + |
| 140 | +decodedTranscriptions = llm_out["decoded_transcripts"] |
| 141 | +with open(input_args.modelPath + "/5gramLLMCompetitionSubmission.txt", "w") as f: |
| 142 | + for x in range(len(decodedTranscriptions)): |
| 143 | + f.write(decodedTranscriptions[x] + "\n") |
0 commit comments