Run this model with HF Jobs
Run zai-org/chatglm-6b 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 to fine-tune https://huggingface.co/zai-org/chatglm-6b. 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/zai-org/chatglm-6b 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.
Instructions to use zai-org/chatglm-6b with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use zai-org/chatglm-6b with Transformers:
# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("zai-org/chatglm-6b", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Merge branch 'main' into dev_pt
Browse filesFiles changed (3)
- README.md+4
- modeling_chatglm.py+154-63
- tokenization_chatglm.py+1-1
10 unmodified lines11121314151627 unmodified lines44454647484910 unmodified lines## 介绍ChatGLM-6B 是一个开源的、支持中英双语问答的对话语言模型,基于 [General Language Model (GLM)](https://github.com/THUDM/GLM) 架构,具有 62 亿参数。结合模型量化技术,用户可以在消费级的显卡上进行本地部署(INT4 量化级别下最低只需 6GB 显存)。ChatGLM-6B 使用了和 [ChatGLM](https://chatglm.cn) 相同的技术,针对中文问答和对话进行了优化。经过约 1T 标识符的中英双语训练,辅以监督微调、反馈自助、人类反馈强化学习等技术的加持,62 亿参数的 ChatGLM-6B 已经能生成相当符合人类偏好的回答。## 软件依赖```shell27 unmodified lines关于更多的使用说明,包括如何运行命令行和网页版本的 DEMO,以及使用模型量化以节省显存,请参考我们的 [Github Repo](https://github.com/THUDM/ChatGLM-6B)。## 协议本仓库的代码依照 [Apache-2.0](LICENSE) 协议开源,ChatGLM-6B 模型的权重的使用则需要遵循 [Model License](MODEL_LICENSE)。10 unmodified lines111213141516171827 unmodified lines464748495051525310 unmodified lines## 介绍ChatGLM-6B 是一个开源的、支持中英双语问答的对话语言模型,基于 [General Language Model (GLM)](https://github.com/THUDM/GLM) 架构,具有 62 亿参数。结合模型量化技术,用户可以在消费级的显卡上进行本地部署(INT4 量化级别下最低只需 6GB 显存)。ChatGLM-6B 使用了和 [ChatGLM](https://chatglm.cn) 相同的技术,针对中文问答和对话进行了优化。经过约 1T 标识符的中英双语训练,辅以监督微调、反馈自助、人类反馈强化学习等技术的加持,62 亿参数的 ChatGLM-6B 已经能生成相当符合人类偏好的回答。ChatGLM-6B is an open bilingual language model based on [General Language Model (GLM)](https://github.com/THUDM/GLM) framework, with 6.2 billion parameters. With the quantization technique, users can deploy locally on consumer-grade graphics cards (only 6GB of GPU memory is required at the INT4 quantization level). ChatGLM-6B uses technology similar to ChatGPT, optimized for Chinese QA and dialogue. The model is trained for about 1T tokens of Chinese and English corpus, supplemented by supervised fine-tuning, feedback bootstrap, and reinforcement learning wit human feedback. With only about 6.2 billion parameters, the model is able to generate answers that are in line with human preference.## 软件依赖```shell27 unmodified lines关于更多的使用说明,包括如何运行命令行和网页版本的 DEMO,以及使用模型量化以节省显存,请参考我们的 [Github Repo](https://github.com/THUDM/ChatGLM-6B)。For more instructions, including how to run CLI and web demos, and model quantization, please refer to our [Github Repo](https://github.com/THUDM/ChatGLM-6B).## 协议本仓库的代码依照 [Apache-2.0](LICENSE) 协议开源,ChatGLM-6B 模型的权重的使用则需要遵循 [Model License](MODEL_LICENSE)。
2 unmodified lines34567891 unmodified line111213141516178 unmodified lines262728293031323334353637383940253 unmodified lines294295296297298299300513 unmodified lines8148158168178188198208214 unmodified lines82682782882983083183283383451 unmodified lines8868878888898908918928938948958968978988996 unmodified lines90690790890991091197 unmodified lines100910101011101210131014101531 unmodified lines1047104810491050105110521053101 unmodified lines11551156115711581159116014 unmodified lines1175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912402 unmodified linesimport mathimport copyimport osimport timeimport torchimport torch.utils.checkpoint1 unmodified linefrom torch import nnfrom torch.nn import CrossEntropyLoss, LayerNormfrom torch.nn.utils import skip_initfrom typing import Optional, Tuple, Union, Listfrom transformers.utils import (add_code_sample_docstrings,8 unmodified linesfrom transformers.modeling_utils import PreTrainedModelfrom transformers.utils import loggingfrom transformers.generation.logits_process import LogitsProcessorfrom transformers.generation.utils import LogitsProcessorListfrom .configuration_chatglm import ChatGLMConfig# flags required to enable jit fusion kernelstorch._C._jit_set_profiling_mode(False)torch._C._jit_set_profiling_executor(False)torch._C._jit_override_can_fuse_on_cpu(True)torch._C._jit_override_can_fuse_on_gpu(True)logger = logging.get_logger(__name__)253 unmodified linesif not (attention_mask == 0).all():# if auto-regressive, skipattention_scores.masked_fill_(attention_mask, -10000.0)dtype = attention_scores.type()attention_scores = attention_scores.float()attention_scores = attention_scores * query_key_layer_scaling_coeff513 unmodified linesreturn past_key_values@staticmethoddef get_masks(seq, device):context_length = seq.index(150004) + 1attention_mask = torch.ones((1, len(seq), len(seq)), device=device)attention_mask.tril_()4 unmodified linesreturn attention_maskdef get_position_ids(self, seq, mask_position, device, gmask=False):context_length = seq.index(150004) + 1if self.position_encoding_2d:seq_length = seq.index(150004)position_ids = torch.arange(context_length, dtype=torch.long, device=device)if not gmask:position_ids[seq_length:] = mask_position51 unmodified linespast_key_values = self.get_prompt(batch_size=input_ids.shape[0], device=input_ids.device)else:past_key_values = tuple([None] * len(self.layers))MASK, gMASK = 150000, 150001mask_token = MASK if MASK in input_ids else gMASKuse_gmask = False if MASK in input_ids else gMASKseq = input_ids[0].tolist()mask_position = seq.index(mask_token)if attention_mask is None:attention_mask = self.get_masks(seq=seq,6 unmodified linesattention_mask = torch.cat((prefix_attention_mask, attention_mask), dim=3)if position_ids is None:position_ids = self.get_position_ids(seq=seq,mask_position=mask_position,97 unmodified linesattention_mask = (attention_mask < 0.5).bool()if self.position_encoding_2d:seq_length = seq.index(150004)position_ids = torch.arange(context_length, dtype=torch.long, device=device)if not gmask:position_ids[seq_length:] = mask_position31 unmodified lines# only last token for input_ids if past is not Noneif past is not None or past_key_values is not None:context_length = seq.index(150004)last_token = input_ids[:, -1].unsqueeze(-1)if self.position_encoding_2d:position_ids = torch.tensor([[[mask_position], [len(seq) - context_length]]], dtype=torch.long,101 unmodified linesfor layer_past in past)@torch.no_grad()def chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, max_length: int = 2048, num_beams=1,do_sample=True, top_p=0.7, temperature=0.95, logits_processor=None, **kwargs):14 unmodified linesinput_ids = tokenizer([prompt], return_tensors="pt", padding=True)input_ids = input_ids.to(self.device)outputs = self.generate(**input_ids, **gen_kwargs)outputs = outputs.tolist()[0][len(input_ids["input_ids"][0]) - 2:]response = tokenizer.decode(outputs)response = response.strip()response = response.replace("[[训练时间]]", "2023年")history = history + [(query, response)]return response, history@torch.no_grad()def generate(self,**kwargs,):MASK, gMASK = 150000, 150001bos, eos = 150004, 150005if "eos_token_id" not in kwargs:kwargs["eos_token_id"] = eostruncate = kwargs.pop("truncate") if "truncate" in kwargs else Falsestop = Falsereturn_seqs = []while True:output_ids = super().generate(**kwargs)return_seqs = []max_length = 0for i in range(output_ids.shape[0]):output_seq = output_ids[i].tolist()if truncate:output_seq = output_seq[len(kwargs["input_ids"][i]) - 2:]mask_token = MASK if MASK in output_seq else gMASKmask_position = output_seq.index(mask_token)bos_position = output_seq.index(bos)if eos in output_seq:eos_position = output_seq.index(eos)else:eos_position = len(output_seq)return_seq = output_seq[:mask_position] + output_seq[bos_position + 1:eos_position] + output_seq[mask_position + 1:bos_position]max_length = max(max_length, len(return_seq))return_seqs.append(return_seq)for i in range(output_ids.shape[0]):return_seqs[i] = [0] * (max_length - len(return_seqs[i])) + return_seqs[i] # paddingif mask_token not in return_seqs[i]:stop = Trueif stop:breakfor return_seq in return_seqs:return_seq += [bos]kwargs['input_ids'] = torch.tensor(return_seqs, dtype=torch.long, device=kwargs['input_ids'].device)return torch.tensor(return_seqs, dtype=torch.long, device=kwargs['input_ids'].device)def quantize(self, bits: int):from .quantization import quantize2 unmodified lines345678910111 unmodified line131415161718198 unmodified lines2829303132333435363738394041424344253 unmodified lines298299300301302303304513 unmodified lines8188198208218228238248254 unmodified lines83083183283383483583683783851 unmodified lines8908918928938948958968976 unmodified lines90490590690790890991091191291391497 unmodified lines101210131014101510161017101831 unmodified lines1050105110521053105410551056101 unmodified lines11581159116011611162116311641165116611671168116911701171117211731174117511761177117814 unmodified lines11931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013312 unmodified linesimport mathimport copyimport osimport warningsimport reimport sysimport torchimport torch.utils.checkpoint1 unmodified linefrom torch import nnfrom torch.nn import CrossEntropyLoss, LayerNormfrom torch.nn.utils import skip_initfrom typing import Optional, Tuple, Union, List, Callablefrom transformers.utils import (add_code_sample_docstrings,8 unmodified linesfrom transformers.modeling_utils import PreTrainedModelfrom transformers.utils import loggingfrom transformers.generation.logits_process import LogitsProcessorfrom transformers.generation.utils import LogitsProcessorList, StoppingCriteriaList, GenerationConfigfrom .configuration_chatglm import ChatGLMConfig# flags required to enable jit fusion kernelsif sys.platform != 'darwin':torch._C._jit_set_profiling_mode(False)torch._C._jit_set_profiling_executor(False)torch._C._jit_override_can_fuse_on_cpu(True)torch._C._jit_override_can_fuse_on_gpu(True)logger = logging.get_logger(__name__)253 unmodified linesif not (attention_mask == 0).all():# if auto-regressive, skipattention_scores.masked_fill_(attention_mask, -10000.0)dtype = attention_scores.dtypeattention_scores = attention_scores.float()attention_scores = attention_scores * query_key_layer_scaling_coeff513 unmodified linesreturn past_key_values@staticmethoddef get_masks(self, seq, device):context_length = seq.index(self.config.bos_token_id) + 1attention_mask = torch.ones((1, len(seq), len(seq)), device=device)attention_mask.tril_()4 unmodified linesreturn attention_maskdef get_position_ids(self, seq, mask_position, device, gmask=False):context_length = len(seq)if self.position_encoding_2d:seq_length = seq.index(self.config.bos_token_id)position_ids = torch.arange(context_length, dtype=torch.long, device=device)if not gmask:position_ids[seq_length:] = mask_position51 unmodified linespast_key_values = self.get_prompt(batch_size=input_ids.shape[0], device=input_ids.device)else:past_key_values = tuple([None] * len(self.layers))seq = input_ids[0].tolist()if attention_mask is None:attention_mask = self.get_masks(seq=seq,6 unmodified linesattention_mask = torch.cat((prefix_attention_mask, attention_mask), dim=3)if position_ids is None:MASK, gMASK = 150000, 150001mask_token = MASK if MASK in input_ids else gMASKuse_gmask = False if MASK in input_ids else gMASKmask_position = seq.index(mask_token)position_ids = self.get_position_ids(seq=seq,mask_position=mask_position,97 unmodified linesattention_mask = (attention_mask < 0.5).bool()if self.position_encoding_2d:seq_length = seq.index(self.config.bos_token_id)position_ids = torch.arange(context_length, dtype=torch.long, device=device)if not gmask:position_ids[seq_length:] = mask_position31 unmodified lines# only last token for input_ids if past is not Noneif past is not None or past_key_values is not None:context_length = seq.index(self.config.bos_token_id)last_token = input_ids[:, -1].unsqueeze(-1)if self.position_encoding_2d:position_ids = torch.tensor([[[mask_position], [len(seq) - context_length]]], dtype=torch.long,101 unmodified linesfor layer_past in past)def process_response(self, response):response = response.strip()response = response.replace("[[训练时间]]", "2023年")punkts = [[",", ","],["!", "!"],[":", ":"],[";", ";"],["\?", "?"],]for item in punkts:response = re.sub(r"([\u4e00-\u9fff])%s" % item[0], r"\1%s" % item[1], response)response = re.sub(r"%s([\u4e00-\u9fff])" % item[0], r"%s\1" % item[1], response)return response@torch.no_grad()def chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, max_length: int = 2048, num_beams=1,do_sample=True, top_p=0.7, temperature=0.95, logits_processor=None, **kwargs):14 unmodified linesinput_ids = tokenizer([prompt], return_tensors="pt", padding=True)input_ids = input_ids.to(self.device)outputs = self.generate(**input_ids, **gen_kwargs)outputs = outputs.tolist()[0][len(input_ids["input_ids"][0]):]response = tokenizer.decode(outputs)response = self.process_response(response)history = history + [(query, response)]return response, history@torch.no_grad()def stream_chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, max_length: int = 2048,do_sample=True, top_p=0.7, temperature=0.95, logits_processor=None, **kwargs):if history is None:history = []if logits_processor is None:logits_processor = LogitsProcessorList()logits_processor.append(InvalidScoreLogitsProcessor())gen_kwargs = {"max_length": max_length, "do_sample": do_sample, "top_p": top_p,"temperature": temperature, "logits_processor": logits_processor, **kwargs}if not history:prompt = queryelse:prompt = ""for i, (old_query, response) in enumerate(history):prompt += "[Round {}]\n问:{}\n答:{}\n".format(i, old_query, response)prompt += "[Round {}]\n问:{}\n答:".format(len(history), query)input_ids = tokenizer([prompt], return_tensors="pt", padding=True)input_ids = input_ids.to(self.device)for outputs in self.stream_generate(**input_ids, **gen_kwargs):outputs = outputs.tolist()[0][len(input_ids["input_ids"][0]):]response = tokenizer.decode(outputs)response = self.process_response(response)new_history = history + [(query, response)]yield response, new_history@torch.no_grad()def stream_generate(self,input_ids,generation_config: Optional[GenerationConfig] = None,logits_processor: Optional[LogitsProcessorList] = None,stopping_criteria: Optional[StoppingCriteriaList] = None,prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,**kwargs,):batch_size, input_ids_seq_length = input_ids.shape[0], input_ids.shape[-1]if generation_config is None:generation_config = self.generation_configgeneration_config = copy.deepcopy(generation_config)model_kwargs = generation_config.update(**kwargs)bos_token_id, eos_token_id = generation_config.bos_token_id, generation_config.eos_token_idif isinstance(eos_token_id, int):eos_token_id = [eos_token_id]has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not Noneif has_default_max_length and generation_config.max_new_tokens is None:warnings.warn(f"Using `max_length`'s default ({generation_config.max_length}) to control the generation length. ""This behaviour is deprecated and will be removed from the config in v5 of Transformers -- we"" recommend using `max_new_tokens` to control the maximum length of the generation.",UserWarning,)elif generation_config.max_new_tokens is not None:generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_lengthif not has_default_max_length:logger.warn(f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. ""Please refer to the documentation for more information. ""(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)",UserWarning,)if input_ids_seq_length >= generation_config.max_length:input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"logger.warning(f"Input length of {input_ids_string} is {input_ids_seq_length}, but `max_length` is set to"f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"" increasing `max_new_tokens`.")# 2. Set generation parameters if not already definedlogits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()logits_processor = self._get_logits_processor(generation_config=generation_config,input_ids_seq_length=input_ids_seq_length,encoder_input_ids=input_ids,prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,logits_processor=logits_processor,)stopping_criteria = self._get_stopping_criteria(generation_config=generation_config, stopping_criteria=stopping_criteria)logits_warper = self._get_logits_warper(generation_config)unfinished_sequences = input_ids.new(input_ids.shape[0]).fill_(1)scores = Nonewhile True:model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)# forward pass to get next tokenoutputs = self(**model_inputs,return_dict=True,output_attentions=False,output_hidden_states=False,)next_token_logits = outputs.logits[:, -1, :]# pre-process distributionnext_token_scores = logits_processor(input_ids, next_token_logits)next_token_scores = logits_warper(input_ids, next_token_scores)# sampleprobs = nn.functional.softmax(next_token_scores, dim=-1)if generation_config.do_sample:next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)else:next_tokens = torch.argmax(probs, dim=-1)# update generated ids, model inputs, and length for next stepinput_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)model_kwargs = self._update_model_kwargs_for_generation(outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder)unfinished_sequences = unfinished_sequences.mul((sum(next_tokens != i for i in eos_token_id)).long())# stop when each sentence is finished, or if we exceed the maximum lengthif unfinished_sequences.max() == 0 or stopping_criteria(input_ids, scores):breakyield input_idsdef quantize(self, bits: int):from .quantization import quantize
298 unmodified lines299300301302303304305298 unmodified lines"""if os.path.isdir(save_directory):vocab_file = os.path.join(save_directory, VOCAB_FILES_NAMES["vocab_file"])else:vocab_file = save_directory298 unmodified lines299300301302303304305298 unmodified lines"""if os.path.isdir(save_directory):vocab_file = os.path.join(save_directory, self.vocab_files_names["vocab_file"])else:vocab_file = save_directory
README.md+4
modeling_chatglm.py+154-63
tokenization_chatglm.py+1-1