Text Generation
Transformers
PyTorch
Chinese
English
codeshell
wisdomshell
pku-kcl
openbankai
custom_code
Run this model with HF Jobs
Run WisdomShell/CodeShell-7B-Chat on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs and TRL to fine-tune https://huggingface.co/WisdomShell/CodeShell-7B-Chat. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/WisdomShell/CodeShell-7B-Chat on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/WisdomShell/CodeShell-7B-Chat. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Quantize for lower memory use
Use HF Jobs to create a 4-bit version of https://huggingface.co/WisdomShell/CodeShell-7B-Chat. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Instructions to use WisdomShell/CodeShell-7B-Chat with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use WisdomShell/CodeShell-7B-Chat with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="WisdomShell/CodeShell-7B-Chat", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("WisdomShell/CodeShell-7B-Chat", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use WisdomShell/CodeShell-7B-Chat with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "WisdomShell/CodeShell-7B-Chat" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "WisdomShell/CodeShell-7B-Chat", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/WisdomShell/CodeShell-7B-Chat
- SGLang
How to use WisdomShell/CodeShell-7B-Chat with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "WisdomShell/CodeShell-7B-Chat" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "WisdomShell/CodeShell-7B-Chat", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "WisdomShell/CodeShell-7B-Chat" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "WisdomShell/CodeShell-7B-Chat", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use WisdomShell/CodeShell-7B-Chat with Docker Model Runner:
docker model run hf.co/WisdomShell/CodeShell-7B-Chat
Update modeling_codeshell.py
Browse files29 unmodified lines30313233343536373839404142436 unmodified lines50515253545556682 unmodified lines73974074174274374417 unmodified lines762763764765766767768769770771110 unmodified lines88288388429 unmodified lines# See the License for the specific language governing permissions and# limitations under the License."""PyTorch CodeShell model."""import mathfrom typing import List, Optional, Tuple, Unionimport torchimport torch.utils.checkpointfrom torch import nnfrom torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELossfrom transformers.activations import ACT2FNfrom transformers.modeling_outputs import (BaseModelOutputWithPastAndCrossAttentions,6 unmodified lines)from .configuration_codeshell import CodeShellConfig# Fused kernels# Use separate functions for each case because conditionals prevent kernel fusion.# TODO: Could have better fused kernels depending on scaling, dropout and head mask.682 unmodified lineshidden_states=all_hidden_states,attentions=all_self_attentions,)@add_start_docstrings(17 unmodified linesdef quantize(self, bits: int):try:import bitsandbytesfrom .quantizer import quantize_onlineexcept ImportError:raise ImportError(f"Needs bitsandbytes to run quantize.")return quantize_online(self, bits)def get_output_embeddings(self):return self.lm_head110 unmodified linestuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),)return reordered_past29 unmodified lines3031323334353637383940414243444546474849506 unmodified lines575859606162682 unmodified lines74574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580617 unmodified lines824825826827828829830831832833110 unmodified lines94494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108629 unmodified lines# See the License for the specific language governing permissions and# limitations under the License."""PyTorch CodeShell model."""import osimport mathfrom typing import List, Optional, Tuple, Union, Callablefrom threading import Threadfrom queue import Queueimport torchimport torch.utils.checkpointfrom torch import nnfrom torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELossfrom transformers import LogitsProcessorList, StoppingCriteriaList, StoppingCriteria, PreTrainedModel, PretrainedConfigfrom transformers.generation.utils import GenerationConfigfrom transformers.activations import ACT2FNfrom transformers.modeling_outputs import (BaseModelOutputWithPastAndCrossAttentions,6 unmodified lines)from .configuration_codeshell import CodeShellConfig# Fused kernels# Use separate functions for each case because conditionals prevent kernel fusion.# TODO: Could have better fused kernels depending on scaling, dropout and head mask.682 unmodified lineshidden_states=all_hidden_states,attentions=all_self_attentions,)class EndOfFunctionCriteria(StoppingCriteria):"""Custom `StoppingCriteria` which checks if all generated functions in the batch are completed."""def __init__(self, input_lengths, eof_strings, tokenizer):self.input_lengths = input_lengthsself.eof_strings = eof_stringsself.tokenizer = tokenizerdef __call__(self, input_ids, scores, **kwargs):"""Returns true if all generated sequences contain any of the end-of-function strings."""decoded_generations = []for _input_ids, input_length in zip(input_ids, self.input_lengths):decoded_generations.append(self.tokenizer.decode(_input_ids[input_length:]))done = []for decoded_generation in decoded_generations:done.append(any([stop_string in decoded_generationfor stop_string in self.eof_strings]))return all(done)class TextIterStreamer:def __init__(self, tokenizer, skip_prompt=False, skip_special_tokens=False):self.tokenizer = tokenizerself.skip_prompt = skip_promptself.skip_special_tokens = skip_special_tokensself.tokens = []self.text_queue = Queue()self.next_tokens_are_prompt = Truedef put(self, value):if self.skip_prompt and self.next_tokens_are_prompt:self.next_tokens_are_prompt = Falseelse:if len(value.shape) > 1:value = value[0]self.tokens.extend(value.tolist())self.text_queue.put(self.tokenizer.decode(self.tokens, skip_special_tokens=self.skip_special_tokens))def end(self):self.text_queue.put(None)def __iter__(self):return selfdef __next__(self):value = self.text_queue.get()if value is None:raise StopIteration()else:return value@add_start_docstrings(17 unmodified linesdef quantize(self, bits: int):try:import bitsandbytesfrom .quantizer import quantizeexcept ImportError:raise ImportError(f"Needs bitsandbytes to run quantize.")return quantize(self, bits)def get_output_embeddings(self):return self.lm_head110 unmodified linestuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),)return reordered_pastdef build_chat_input(self, query, history, tokenizer, max_new_tokens=None):user_name = "\n## human:"ai_name = "\n## assistant: "stop = '|<end>|'prompt = ''for q, r in history:prompt += f"{user_name}{q}{stop}"prompt += f"{ai_name}{r}{stop}"prompt += f"{user_name}{query}{stop}"prompt += ai_name.rstrip()max_new_tokens = max_new_tokens or self.generation_config.max_new_tokensmax_input_tokens = self.config.n_positions - max_new_tokensinput_tokens = tokenizer.encode(prompt)input_tokens = input_tokens[-max_input_tokens:] # truncate leftreturn torch.LongTensor([input_tokens]).to(self.device)def chat(self, query, history, tokenizer, stream=False,generation_config: Optional[GenerationConfig]=None):generation_config = generation_config or self.generation_configinput_ids = self.build_chat_input(query, history, tokenizer, generation_config.max_new_tokens)stopping_criteria = StoppingCriteriaList([EndOfFunctionCriteria([len(input_ids[0])], ['|<end>|', '<|endoftext|>'], tokenizer)])if stream:streamer = TextIterStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)Thread(target=self.generate, kwargs=dict(inputs=input_ids, streamer=streamer,stopping_criteria = stopping_criteria,generation_config=generation_config,)).start()return streamerelse:outputs = self.generate(input_ids, generation_config=generation_config, stopping_criteria = stopping_criteria)response = tokenizer.decode(outputs[0][len(input_ids[0]):], skip_special_tokens=True)return responsedef generate_stream(self, prompt, tokenizer, generation_config=None, **kwargs):generation_config = generation_config or self.generation_configmax_input_tokens = self.config.n_positions - self.generation_config.max_new_tokensinput_ids = tokenizer.encode(prompt)input_ids = input_ids[-max_input_tokens:] # truncate leftstopping_criteria = StoppingCriteriaList([EndOfFunctionCriteria([len(input_ids[0])], ['|<end>|', '<|endoftext|>'], tokenizer)])streamer = TextIterStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)Thread(target=self.generate, kwargs=dict(inputs=input_ids, stopping_criteria=stopping_criteria, **kwargs)).start()return streamerclass CodeShell4bitForCausalLM(CodeShellForCausalLM):def __init__(self, config):CodeShellPreTrainedModel.__init__(self, config)self.transformer = CodeShellModel(config)self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)try:import bitsandbytesfrom .quantizer import quantize_offlinequantize_offline(self)except ImportError:raise ImportError(f"Needs bitsandbytes to run quantize.")self.post_init()@classmethoddef from_pretrained(cls,pretrained_model_name_or_path: Optional[Union[str, os.PathLike]],*model_args,config: Optional[Union[PretrainedConfig, str, os.PathLike]] = None,cache_dir: Optional[Union[str, os.PathLike]] = None,ignore_mismatched_sizes: bool = False,force_download: bool = False,local_files_only: bool = False,token: Optional[Union[str, bool]] = None,revision: str = "main",use_safetensors: bool = None,**kwargs,):if not isinstance(config, PretrainedConfig):config_path = config if config is not None else pretrained_model_name_or_pathconfig, _ = cls.config_class.from_pretrained(config_path,cache_dir=cache_dir,return_unused_kwargs=True,force_download=force_download,resume_download=False,proxies=None,local_files_only=local_files_only,token=token,revision=revision,subfolder="",_from_auto=False,_from_pipeline=None,**kwargs,)# Load config if we don't provide a configurationfrom .quantizer import load_state_dict_for_qunantied_modelmodel = cls(config)state_dict = torch.load(os.path.join(pretrained_model_name_or_path, 'pytorch_model.bin'), map_location="cpu")model = load_state_dict_for_qunantied_model(model, state_dict)model.eval()# If it is a model with generation capabilities, attempt to load the generation configif model.can_generate():try:model.generation_config = GenerationConfig.from_pretrained(pretrained_model_name_or_path,cache_dir=cache_dir,force_download=force_download,resume_download=False,proxies=None,local_files_only=local_files_only,token=token,revision=revision,subfolder="",_from_auto=False,_from_pipeline=None,**kwargs,)except (OSError, TypeError):passdevice_map = kwargs.pop("device_map", None)if device_map is not None:model = model.to(torch.device(device_map))return model
modeling_codeshell.py+206-4