ChatGLM-6B

repository·main·Indexed 12 days ago

https://github.com/zai-org/chatglm-6b

An open-source bilingual (Chinese and English) conversational language model with 6.2 billion parameters. It supports local deployment on consumer-grade GPUs with as little as 6GB VRAM using INT4 quantization and provides efficient fine-tuning options via P-Tuning v2 or full parameter fine-tuning with DeepSpeed.

Tokens
8.4K
Snippets
29
Records
41
Agent score
95%

What's inside ChatGLM-6B

  1. Overview of ChatGLM-6B

    main

    ChatGLM-6B is an open-source, bilingual (Chinese and English) conversational language model based on the General Language Model (GLM) architecture with 6.2 billion parameters. It is optimized for Chinese question-answering and dialogue, similar to ChatGPT.

    Key features include:

    • Local Deployment: Supports deployment on consumer-grade GPUs. Using INT4 quantization, it requires as little as 6GB of VRAM.
    • Efficient Fine-tuning: Supports P-Tuning v2 for efficient parameter fine-tuning, requiring as little as 7GB of VRAM for INT4 quantization.
    • Open Access: Weights are fully open for academic research and allow free commercial use after registration via a provided questionnaire.
  2. Evolution and Updates of ChatGLM Models

    main

    The ChatGLM family has evolved through several key releases:

    • CodeGeeX2: A code generation model based on ChatGLM2-6B. It features significantly improved coding capabilities (e.g., +321% in Rust on HumanEval-X), supports up to 8192 sequence length, and can run on 6GB VRAM after quantization.
    • ChatGLM2-6B: An upgrade to the original ChatGLM-6B. It features:
      • Higher Performance: Significant improvements in MMLU, CEval, GSM8K, and BBH benchmarks.
      • Longer Context: Uses FlashAttention to extend context length from 2K to 32K (with 8K used during dialogue training).
      • Efficient Inference: Uses Multi-Query Attention to increase inference speed by 42% and improve VRAM efficiency (8K dialogue length supported with 6GB VRAM via INT4).
    • VisualGLM-6B: A multimodal model for image understanding. Requires SwissArmyTransformer and torchvision to run via cli_demo_vision.py or web_demo_vision.py.
    • WebGLM: A research work supporting long answers with accurate citations using web information.
  3. Understand the limitations of ChatGLM-6B

    main

    ChatGLM-6B is a small-scale model (6B parameters) and has several known limitations that developers should account for in their applications:

    • Limited Model Capacity: Due to its size, it has weaker memory and language capabilities compared to larger models. It may generate incorrect factual information and struggles with complex logic tasks such as mathematics and programming.
    • Potential for Harmful or Biased Content: As a model only partially aligned with human intent, it may generate offensive, biased, or harmful content.
    • Weak English Proficiency: The training data is predominantly Chinese. English instructions may result in lower quality responses, contradictions with Chinese context, or mixed Chinese-English output.
    • Susceptibility to Misleading Prompts: The model has weaker conversational stability and 'self-awareness.' It can be easily misled into providing incorrect information regarding its own identity or facts.
  4. Load ChatGLM-6B model locally

    main

    If downloading from Hugging Face is slow or fails, you can clone the model repository using Git LFS and load it from your local filesystem.

    1. Install Git LFS.
    2. Clone the model:
      git clone https://huggingface.co/THUDM/chatglm-6b
    3. In your Python code, replace "THUDM/chatglm-6b" with the absolute path to your local folder.

    Optional: To fix the model implementation to a specific version, run:

    git checkout v1.1.0
    git clone https://huggingface.co/THUDM/chatglm-6b
  5. Fine-tune ChatGLM-6B using P-Tuning-v2

    main

    The repository includes an implementation of parameter-efficient tuning based on P-Tuning-v2.

    When using the INT4 quantization level, the minimum GPU memory requirement for model tuning is approximately 7GB. For detailed instructions on the tuning process, refer to the ptuning/README.md file.

  6. Install ChatGLM-6B Dependencies

    main

    Install the required Python dependencies using pip:

    pip install -r requirements.txt

    Note on versions:

    • transformers library: Recommended version is 4.27.1, but any version $\ge$ 4.23.1 is acceptable.

    CPU Runtime Requirements: If running quantized models on a CPU, you must install gcc and openmp.

    • Linux: Most distributions have these installed by default.
    • Windows: Install TDM-GCC and ensure openmp is checked. (Tested with TDM-GCC 10.3.0)
    • MacOS: Refer to the FAQ for OpenMP installation.
    pip install -r requirements.txt
  7. Access GLM-4 Models and APIs

    main

    The latest GLM-4 models are available through several channels:

    • Open Source Models: The GLM-4-9B series is available on GitHub.
    • ChatGLM Web Experience: Use 智谱清言 to experience the latest GLM-4 features, including GLMs and All tools.
    • API Platform: Access a variety of models including GLM-4-0520, GLM-4-air, GLM-4-airx, GLM-4-flash, GLM-4, GLM-3-Turbo, CharacterGLM-3, and CogView-3 via the Zhipu AI Open Platform.
      • Note: GLM-4 and GLM-3-Turbo support advanced features like System Prompt, Function Call, Retrieval, and Web_Search.
    • API Tutorials: Use the GLM-4 API Cookbook for tutorials and basic applications.
  8. Deploy ChatGLM-6B with P-Tuning v2 checkpoints

    main

    To deploy a model using a P-Tuning v2 checkpoint (which only contains PrefixEncoder parameters), follow these steps:

    1. Load the Tokenizer:
    from transformers import AutoConfig, AutoModel, AutoTokenizer
    
    tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True)
    1. Load the Base Model and Inject Prefix Weights: Note: Replace pre_seq_len with your actual training value and THUDM/chatglm-6b with your local model path if necessary.
    import torch
    import os
    from transformers import AutoConfig, AutoModel
    
    config = AutoConfig.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True, pre_seq_len=128)
    model = AutoModel.from_pretrained("THUDM/chatglm-6b", config=config, trust_remote_code=True)
    
    # Load PrefixEncoder weights
    prefix_state_dict = torch.load(os.path.join(CHECKPOINT_PATH, "pytorch_model.bin"))
    new_prefix_state_dict = {}
    for k, v in prefix_state_dict.items():
        if k.startswith("transformer.prefix_encoder."):
            new_prefix_state_dict[k[len("transformer.prefix_encoder."):]] = v
    model.transformer.prefix_encoder.load_state_dict(new_prefix_state_dict)
    1. Quantization and Inference:
    # Comment out the following line if you don't use quantization
    model = model.quantize(4)
    model = model.half().cuda()
    model.transformer.prefix_encoder.float()
    model = model.eval()
    
    response, history = model.chat(tokenizer, "你好", history=[])

    If you are using a full parameter checkpoint or a full finetune, load it directly:

    model = AutoModel.from_pretrained(CHECKPOINT_PATH, trust_remote_code=True)
    from transformers import AutoConfig, AutoModel, AutoTokenizer
    
    # 1. Load Tokenizer
    tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True)
    
    # 2. Load P-Tuning v2 Checkpoint
    config = AutoConfig.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True, pre_seq_len=128)
    model = AutoModel.from_pretrained("THUDM/chatglm-6b", config=config, trust_remote_code=True)
    prefix_state_dict = torch.load(os.path.join(CHECKPOINT_PATH, "pytorch_model.bin"))
    new_prefix_state_dict = {}
    for k, v in prefix_state_dict.items():
        if k.startswith("transformer.prefix_encoder."):
            new_prefix_state_dict[k[len("transformer.prefix_encoder."):]] = v
    model.transformer.prefix_encoder.load_state_dict(new_prefix_state_dict)
    
    # 3. Quantize and Chat
    model = model.quantize(4)
    model = model.half().cuda()
    model.transformer.prefix_encoder.float()
    model = model.eval()
    
    response, history = model.chat(tokenizer, "你好", history=[])
  9. Quantize ChatGLM-6B for Low VRAM Usage

    main

    If you have limited GPU VRAM, you can quantize the model during loading. This reduces VRAM usage but may introduce slight performance loss.

    On-the-fly Quantization (8-bit or 4-bit):

    # Quantize to 8-bit
    model = AutoModel.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True).quantize(8).half().cuda()

    Loading Pre-quantized Models: To save system memory during the quantization process, load pre-quantized models directly:

    • For INT4: Use THUDM/chatglm-6b-int4 (requires ~5.2GB RAM).
    • For INT8: Use THUDM/chatglm-6b-int8.
    model = AutoModel.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True).quantize(8).half().cuda()
  10. Deploy ChatGLM-6B on CPU or Mac

    main

    CPU Deployment

    If no GPU is available, load the model in float mode (requires ~32GB RAM):

    model = AutoModel.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True).float()

    Mac Deployment (Apple Silicon/AMD)

    You can use the mps backend for GPU acceleration. Note that you must load the model from a local path and install PyTorch-Nightly (version 2.1.0.dev2023xxxx or similar).

    Using MPS (GPU):

    model = AutoModel.from_pretrained("your local path", trust_remote_code=True).half().to('mps')

    Note: Half-precision on Mac requires ~13GB RAM. If memory is low, use the INT4 quantized model on CPU instead.

    Using CPU on Mac:

    model = AutoModel.from_pretrained("THUDM/chatglm-6b-int4", trust_remote_code=True).float()