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
支持batch形式的对话
#60
by curlyfu - opened
720 unmodified lines7217227237247257267274 unmodified lines73273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776815 unmodified lines784785786787788789790791792793794795796440 unmodified lines123712381239124012411242124344 unmodified lines128812891290129112921293720 unmodified linesThis model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class.Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to generalusage and behavior.Parameters:config ([`~ChatGLM6BConfig`]): Model configuration class with all the parameters of the model.Initializing with a config file does not load the weights associated with the model, only the configuration.4 unmodified linesArgs:input_ids (`torch.LongTensor` of shape `({0})`):Indices of input sequence tokens in the vocabulary.Indices can be obtained using [`ChatGLM6BTokenizer`].See [`PreTrainedTokenizer.encode`] and[`PreTrainedTokenizer.__call__`] for details.[What are input IDs?](../glossary#input-ids)attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:- 1 for tokens that are **not masked**,- 0 for tokens that are **masked**.[What are attention masks?](../glossary#attention-mask)token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`:- 0 corresponds to a *sentence A* token,- 1 corresponds to a *sentence B* token.[What are token type IDs?](../glossary#token-type-ids)position_ids (`torch.LongTensor` of shape `({0})`, *optional*):Indices of positions of each input sequence tokens in the position embeddings.Selected in the range `[0, config.max_position_embeddings - 1]`.[What are position IDs?](../glossary#position-ids)head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:- 1 indicates the head is **not masked**,- 0 indicates the head is **masked**.inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.This is useful if you want more control over how to convert *input_ids* indices into associated vectors15 unmodified lines)class ChatGLMModel(ChatGLMPreTrainedModel):"""The model can behave as an encoder (with only self-attention) as wellas a decoder, in which case a layer of cross-attention is added betweenthe self-attention layers, following the architecture described in [Attention isall you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani,Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.To behave as an decoder the model needs to be initialized with the`is_decoder` argument of the configuration set to `True`.To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder`440 unmodified linesThis function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or[`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correctbeam_idx at every generation step.Output shares the same memory storage as `past`."""return tuple(44 unmodified linesresponse = 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,720 unmodified lines7217227237247257264 unmodified lines73173273373473573673773873974074174274374474574674774874975075175275375475575675775815 unmodified lines774775776777778779780781782783784440 unmodified lines12251226122712281229123044 unmodified lines127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310720 unmodified linesThis model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class.Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to generalusage and behavior.Parameters:config ([`~ChatGLM6BConfig`]): Model configuration class with all the parameters of the model.Initializing with a config file does not load the weights associated with the model, only the configuration.4 unmodified linesArgs:input_ids (`torch.LongTensor` of shape `({0})`):Indices of input sequence tokens in the vocabulary.Indices can be obtained using [`ChatGLM6BTokenizer`].See [`PreTrainedTokenizer.encode`] and[`PreTrainedTokenizer.__call__`] for details.[What are input IDs?](../glossary#input-ids)attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:- 1 for tokens that are **not masked**,- 0 for tokens that are **masked**.[What are attention masks?](../glossary#attention-mask)token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`:- 0 corresponds to a *sentence A* token,- 1 corresponds to a *sentence B* token.[What are token type IDs?](../glossary#token-type-ids)position_ids (`torch.LongTensor` of shape `({0})`, *optional*):Indices of positions of each input sequence tokens in the position embeddings.Selected in the range `[0, config.max_position_embeddings - 1]`.[What are position IDs?](../glossary#position-ids)head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:- 1 indicates the head is **not masked**,- 0 indicates the head is **masked**.inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.This is useful if you want more control over how to convert *input_ids* indices into associated vectors15 unmodified lines)class ChatGLMModel(ChatGLMPreTrainedModel):"""The model can behave as an encoder (with only self-attention) as wellas a decoder, in which case a layer of cross-attention is added betweenthe self-attention layers, following the architecture described in [Attention isall you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani,Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.To behave as an decoder the model needs to be initialized with the`is_decoder` argument of the configuration set to `True`.To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder`440 unmodified linesThis function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or[`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correctbeam_idx at every generation step.Output shares the same memory storage as `past`."""return tuple(44 unmodified linesresponse = self.process_response(response)history = history + [(query, response)]return response, history@torch.no_grad()def chat_batch(self, tokenizer, querys=List[str], historys=List[List[Tuple[str, str]]], max_length: int = 2048, num_beams=1,do_sample=True, top_p=0.7, temperature=0.95, logits_processor=None, **kwargs):responses = []prompts = []for query, history in zip(querys, historys):if history is None:history = []if logits_processor is None:logits_processor = LogitsProcessorList()logits_processor.append(InvalidScoreLogitsProcessor())gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "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)prompts.append(prompt)inputs = tokenizer(prompts, return_tensors="pt", padding=True)inputs = inputs.to(self.device)outputs = self.generate(**inputs, **gen_kwargs)outputs = outputs.tolist()outputs = [x[len(inputs["input_ids"][0]):] for x in outputs]responses = [tokenizer.decode(output) for output in outputs]responses = [self.process_response(response) for response in responses]return responses@torch.no_grad()def stream_chat(self, tokenizer, query: str, history: List[Tuple[str, str]] = None, max_length: int = 2048,
modeling_chatglm.py+30-13