Spaces:
Configuration error
Configuration error
Upload inference.py
Browse files41 unmodified lines42434445464748495051525354555635 unmodified lines929394959697988 unmodified lines1071081091101111121131141151161171181193 unmodified lines1231241251261271281291301311321331341351361371381391401411422 unmodified lines1451461471481491501515 unmodified lines15715815916016116216316416516616716816917017143 unmodified lines21521621721821922022110 unmodified lines23223323423523623723817 unmodified lines25625725825926026126226326426526626726826927027122 unmodified lines29429529629729829930030130230330430530630730830931031131231331421 unmodified lines3363373383393403413424 unmodified lines34734834935035135235335435535635735835936036136216 unmodified lines37938038138238338438538638738838939039139239341 unmodified linesmodel = NotaGenLMHeadModel(encoder_config=patch_config, decoder_config=byte_config).to(device)def download_model_weights():weights_path = "weights_notagenx_p_size_16_p_length_1024_p_layers_20_h_size_1280.pth"local_weights_path = os.path.join(os.getcwd(), weights_path)# Check if weights already exist locallyif os.path.exists(local_weights_path):logger.info(f"Model weights already exist at {local_weights_path}")return local_weights_pathlogger.info("Downloading model weights from HuggingFace Hub...")try:# Download from HuggingFace35 unmodified linesmodel = prepare_model_for_kbit_training(model,use_gradient_checkpointing=False)print("Parameter Number: " + str(sum(p.numel() for p in model.parameters() if p.requires_grad)))8 unmodified linesdef postprocess_inst_names(abc_text):with open('standard_inst_names.txt', 'r', encoding='utf-8') as f:standard_instruments_list = [line.strip() for line in f if line.strip()]with open('instrument_mapping.json', 'r', encoding='utf-8') as f:instrument_mapping = json.load(f)abc_lines = abc_text.split('\n')abc_lines = list(filter(None, abc_lines))abc_lines = [line + '\n' for line in abc_lines]3 unmodified linesmatch = re.search(r'nm="([^"]*)"', line)if match:inst_name = match.group(1)# Check if the instrument name is already standardif inst_name in standard_instruments_list:continue# Find the most similar key in instrument_mappingmatching_key = difflib.get_close_matches(inst_name, list(instrument_mapping.keys()), n=1, cutoff=0.6)if matching_key:# Replace the instrument name with the standardized versionreplacement = instrument_mapping[matching_key[0]]new_line = line.replace(f'nm="{inst_name}"', f'nm="{replacement}"')abc_lines[i] = new_line# Combine the lines back into a single stringprocessed_abc_text = ''.join(abc_lines)return processed_abc_text2 unmodified linesdef complete_brackets(s):stack = []bracket_map = {'{': '}', '[': ']', '(': ')'}# Iterate through each character, handle bracket matchingfor char in s:if char in bracket_map:5 unmodified linesif stack and stack[-1] == key:stack.pop()break # Found matching right bracket, process next character# Complete missing right brackets (in reverse order of remaining left brackets in stack)completion = ''.join(bracket_map[c] for c in reversed(stack))return s + completiondef rest_unreduce(abc_lines):tunebody_index = Nonefor i in range(len(abc_lines)):if abc_lines[i].startswith('%%score'):43 unmodified linesline_bar_dict[key] = value# calculate duration and collect barlinedur_dict = {}for symbol, bartext in line_bar_dict.items():right_barline = ''.join(re.split(Barline_regexPattern, bartext)[-2:])bartext = bartext[:-len(right_barline)]10 unmodified linestry:ref_dur = max(dur_dict, key=dur_dict.get)except:pass # use last ref_durif i == 0:prefix_left_barline = line.split('[V:')[0]17 unmodified linesreturn unreduced_linesdef inference_patch(period, composer, instrumentation):prompt_lines=['%' + period + '\n','%' + composer + '\n','%' + instrumentation + '\n']while True:22 unmodified linestunebody_flag = Falsewith torch.inference_mode():while True:with torch.autocast(device_type='cuda', dtype=torch.float16):predicted_patch = model.generate(input_patches.unsqueeze(0),top_k=TOP_K,top_p=TOP_P,temperature=TEMPERATURE)if not tunebody_flag and patchilizer.decode([predicted_patch]).startswith('[r:'): # 初次进入tunebody,必须以[r:0/开头tunebody_flag = Truer0_patch = torch.tensor([ord(c) for c in '[r:0/']).unsqueeze(0).to(device)temp_input_patches = torch.concat([input_patches, r0_patch], axis=-1)predicted_patch = model.generate(temp_input_patches.unsqueeze(0),top_k=TOP_K,top_p=TOP_P,temperature=TEMPERATURE)predicted_patch = [ord(c) for c in '[r:0/'] + predicted_patchif predicted_patch[0] == patchilizer.bos_token_id and predicted_patch[1] == patchilizer.eos_token_id:end_flag = True21 unmodified linesif len(byte_list) > 102400:failure_flag = Truebreakif time.time() - start_time > 10 * 60:failure_flag = Truebreak4 unmodified linescontext_tunebody = ''.join(context_tunebody_byte_list)if '\n' not in context_tunebody:break # Generated content is all metadata, abandoncontext_tunebody_liness = context_tunebody.split('\n')if not context_tunebody.endswith('\n'):context_tunebody_liness = [context_tunebody_liness[i] + '\n' for i in range(len(context_tunebody_liness) - 1)] + [context_tunebody_liness[-1]]else:context_tunebody_liness = [context_tunebody_liness[i] + '\n' for i in range(len(context_tunebody_liness))]cut_index = len(context_tunebody_liness) // 2abc_code_slice = metadata + ''.join(context_tunebody_liness[-cut_index:])input_patches = patchilizer.encode_generate(abc_code_slice)16 unmodified linesfailure_flag = Truepasselse:unreduced_abc_lines = [line for line in unreduced_abc_lines if not(line.startswith('%') and not line.startswith('%%'))]unreduced_abc_lines = ['X:1\n'] + unreduced_abc_linesunreduced_abc_text = ''.join(unreduced_abc_lines)return unreduced_abc_textif __name__ == '__main__':inference_patch('Classical', 'Beethoven, Ludwig van', 'Orchestral')41 unmodified lines4243444546474849505152535455565735 unmodified lines939495969798998 unmodified lines1081091101111121131141151161171181193 unmodified lines1231241251261271281291301311321331341351361371381391401411422 unmodified lines1451461471481491501515 unmodified lines15715815916016116216316416516616716816943 unmodified lines21321421521621721821910 unmodified lines23023123223323423523617 unmodified lines25425525625725825926026126226326422 unmodified lines28728828929029129229329429529629729829930030130230330430530630730821 unmodified lines3303313323333343353364 unmodified lines34134234334434534634734834935035135235335435535635735835916 unmodified lines37637737837938038138238338438538638738841 unmodified linesmodel = NotaGenLMHeadModel(encoder_config=patch_config, decoder_config=byte_config).to(device)def download_model_weights():weights_path = "weights_notagenx_p_size_16_p_length_1024_p_layers_20_h_size_1280.pth"local_weights_path = os.path.join(os.getcwd(), weights_path)# Check if weights already exist locallyif os.path.exists(local_weights_path):logger.info(f"Model weights already exist at {local_weights_path}")return local_weights_pathlogger.info("Downloading model weights from HuggingFace Hub...")try:# Download from HuggingFace35 unmodified linesmodel = prepare_model_for_kbit_training(model,use_gradient_checkpointing=False)print("Parameter Number: " + str(sum(p.numel() for p in model.parameters() if p.requires_grad)))8 unmodified linesdef postprocess_inst_names(abc_text):with open('standard_inst_names.txt', 'r', encoding='utf-8') as f:standard_instruments_list = [line.strip() for line in f if line.strip()]with open('instrument_mapping.json', 'r', encoding='utf-8') as f:instrument_mapping = json.load(f)abc_lines = abc_text.split('\n')abc_lines = list(filter(None, abc_lines))abc_lines = [line + '\n' for line in abc_lines]3 unmodified linesmatch = re.search(r'nm="([^"]*)"', line)if match:inst_name = match.group(1)# Check if the instrument name is already standardif inst_name in standard_instruments_list:continue# Find the most similar key in instrument_mappingmatching_key = difflib.get_close_matches(inst_name, list(instrument_mapping.keys()), n=1, cutoff=0.6)if matching_key:# Replace the instrument name with the standardized versionreplacement = instrument_mapping[matching_key[0]]new_line = line.replace(f'nm="{inst_name}"', f'nm="{replacement}"')abc_lines[i] = new_line# Combine the lines back into a single stringprocessed_abc_text = ''.join(abc_lines)return processed_abc_text2 unmodified linesdef complete_brackets(s):stack = []bracket_map = {'{': '}', '[': ']', '(': ')'}# Iterate through each character, handle bracket matchingfor char in s:if char in bracket_map:5 unmodified linesif stack and stack[-1] == key:stack.pop()break # Found matching right bracket, process next character# Complete missing right brackets (in reverse order of remaining left brackets in stack)completion = ''.join(bracket_map[c] for c in reversed(stack))return s + completiondef rest_unreduce(abc_lines):tunebody_index = Nonefor i in range(len(abc_lines)):if abc_lines[i].startswith('%%score'):43 unmodified linesline_bar_dict[key] = value# calculate duration and collect barlinedur_dict = {}for symbol, bartext in line_bar_dict.items():right_barline = ''.join(re.split(Barline_regexPattern, bartext)[-2:])bartext = bartext[:-len(right_barline)]10 unmodified linestry:ref_dur = max(dur_dict, key=dur_dict.get)except:pass # use last ref_durif i == 0:prefix_left_barline = line.split('[V:')[0]17 unmodified linesreturn unreduced_linesdef inference_patch(period, composer, instrumentation):prompt_lines = ['%' + period + '\n','%' + composer + '\n','%' + instrumentation + '\n']while True:22 unmodified linestunebody_flag = Falsewith torch.inference_mode():while True:with torch.autocast(device_type='cuda', dtype=torch.float16):predicted_patch = model.generate(input_patches.unsqueeze(0),top_k=TOP_K,top_p=TOP_P,temperature=TEMPERATURE)if not tunebody_flag and patchilizer.decode([predicted_patch]).startswith('[r:'): # 初次进入tunebody,必须以[r:0/开头tunebody_flag = Truer0_patch = torch.tensor([ord(c) for c in '[r:0/']).unsqueeze(0).to(device)temp_input_patches = torch.concat([input_patches, r0_patch], axis=-1)predicted_patch = model.generate(temp_input_patches.unsqueeze(0),top_k=TOP_K,top_p=TOP_P,temperature=TEMPERATURE)predicted_patch = [ord(c) for c in '[r:0/'] + predicted_patchif predicted_patch[0] == patchilizer.bos_token_id and predicted_patch[1] == patchilizer.eos_token_id:end_flag = True21 unmodified linesif len(byte_list) > 102400:failure_flag = Truebreakif time.time() - start_time > 10 * 60:failure_flag = Truebreak4 unmodified linescontext_tunebody = ''.join(context_tunebody_byte_list)if '\n' not in context_tunebody:break # Generated content is all metadata, abandoncontext_tunebody_lines = context_tunebody.strip().split('\n')if not context_tunebody.endswith('\n'):context_tunebody_lines = [context_tunebody_lines[i] + '\n' for i inrange(len(context_tunebody_lines) - 1)] + [context_tunebody_lines[-1]]else:context_tunebody_lines = [context_tunebody_lines[i] + '\n' for i inrange(len(context_tunebody_lines))]cut_index = len(context_tunebody_lines) // 2abc_code_slice = metadata + ''.join(context_tunebody_lines[-cut_index:])input_patches = patchilizer.encode_generate(abc_code_slice)16 unmodified linesfailure_flag = Truepasselse:unreduced_abc_lines = [line for line in unreduced_abc_lines ifnot (line.startswith('%') and not line.startswith('%%'))]unreduced_abc_lines = ['X:1\n'] + unreduced_abc_linesunreduced_abc_text = ''.join(unreduced_abc_lines)return unreduced_abc_textif __name__ == '__main__':inference_patch('Classical', 'Beethoven, Ludwig van', 'Orchestral')
inference.py+38-43