char-fork/llama.cpp
git clone https://git.t4t.associates/char-fork/llama.cpp
5137da7b8
char/aliceai-t5-moe
1#!/usr/bin/env python 2''' 3Fetches the Jinja chat template of a HuggingFace model. 4If a model has multiple chat templates, you can specify the variant name. 5 6Syntax: 7./scripts/get_chat_template.py model_id [variant] 8 9Examples: 10./scripts/get_chat_template.py CohereForAI/c4ai-command-r-plus tool_use 11./scripts/get_chat_template.py microsoft/Phi-3.5-mini-instruct 12''' 13 14import json 15import re 16import sys 17 18 19def get_chat_template (model_id ,variant = None ): 20try : 21# Use huggingface_hub library if available. 22# Allows access to gated models if the user has access and ran `huggingface-cli login`. 23from huggingface_hub import hf_hub_download 24with open (hf_hub_download (repo_id = model_id ,filename = "tokenizer_config.json" ),encoding = "utf-8" )as f : 25config_str = f .read () 26except ImportError : 27import requests 28assert re .match (r"^[\w.-]+/[\w.-]+$" ,model_id ),f"Invalid model ID: { model_id } " 29response = requests .get (f"https://huggingface.co/ { model_id } /resolve/main/tokenizer_config.json" ) 30if response .status_code == 401 : 31raise Exception ('Access to this model is gated, please request access, authenticate with `huggingface-cli login` and make sure to run `pip install huggingface_hub`' ) 32response .raise_for_status () 33config_str = response .text 34 35try : 36config = json .loads (config_str ) 37except json .JSONDecodeError : 38# Fix https://huggingface.co/NousResearch/Meta-Llama-3-8B-Instruct/blob/main/tokenizer_config.json 39# (Remove extra '}' near the end of the file) 40config = json .loads (re .sub (r'\}([\n\s]*\}[\n\s]*\],[\n\s]*"clean_up_tokenization_spaces")' ,r'\1' ,config_str )) 41 42chat_template = config ['chat_template' ] 43if isinstance (chat_template ,str ): 44return chat_template 45else : 46variants = { 47ct ['name' ]:ct ['template' ] 48for ct in chat_template 49 } 50 51def format_variants (): 52return ', ' .join (f'" { v } "' for v in variants .keys ()) 53 54if variant is None : 55if 'default' not in variants : 56raise Exception (f'Please specify a chat template variant (one of { format_variants () } )' ) 57variant = 'default' 58sys .stderr .write (f'Note: picked "default" chat template variant (out of { format_variants () } )\n' ) 59elif variant not in variants : 60raise Exception (f"Variant { variant } not found in chat template (found { format_variants () } )" ) 61 62return variants [variant ] 63 64 65def main (args ): 66if len (args )< 1 : 67raise ValueError ("Please provide a model ID and an optional variant name" ) 68model_id = args [0 ] 69variant = None if len (args )< 2 else args [1 ] 70 71template = get_chat_template (model_id ,variant ) 72sys .stdout .write (template ) 73 74 75if __name__ == '__main__' : 76main (sys .argv [1 :])