vllm icon indicating copy to clipboard operation
vllm copied to clipboard

[Core] Support loading GGUF model

Open Isotr0py opened this issue 1 year ago • 12 comments

FILL IN THE PR DESCRIPTION HERE

Related issue: #1002

Features:

  • This PR adds support for loading GGUF format model
  • This PR will also add gguf to requirements.
  • Support k-quants and imatrix-quants inference.
  • Currently, LLaMa, Mistral and Qwen2 are supported.

Some issues:

  • To use imatrix-quants, gguf installation from source is required.
  • To run Qwen2 gguf model, gguf installation from source is required as well.

TODO:

  • [x] Support loading model from GGUF format
  • [x] ~~Implement dequantize Q8_0 and Q4_0 tensors during inference instead of pre-dequantize in model loading~~
  • [x] Add gguf and update transformers in requirements.txt
  • [x] Add GGUF model tests

BEFORE SUBMITTING, PLEASE READ THE CHECKLIST BELOW AND FILL IN THE DESCRIPTION ABOVE


PR Checklist (Click to Expand)

Thank you for your contribution to vLLM! Before submitting the pull request, please ensure the PR meets the following criteria. This helps vLLM maintain the code quality and improve the efficiency of the review process.

PR Title and Classification

Only specific types of PRs will be reviewed. The PR title is prefixed appropriately to indicate the type of change. Please use one of the following:

  • [Bugfix] for bug fixes.
  • [CI/Build] for build or continuous integration improvements.
  • [Doc] for documentation fixes and improvements.
  • [Model] for adding a new model or improving an existing model. Model name should appear in the title.
  • [Frontend] For changes on the vLLM frontend (e.g., OpenAI API server, LLM class, etc.)
  • [Kernel] for changes affecting CUDA kernels or other compute kernels.
  • [Core] for changes in the core vLLM logic (e.g., LLMEngine, AsyncLLMEngine, Scheduler, etc.)
  • [Hardware][Vendor] for hardware-specific changes. Vendor name should appear in the prefix (e.g., [Hardware][AMD]).
  • [Misc] for PRs that do not fit the above categories. Please use this sparingly.

Note: If the PR spans more than one category, please include all relevant prefixes.

Code Quality

The PR need to meet the following code quality standards:

  • We adhere to Google Python style guide and Google C++ style guide.
  • Pass all linter checks. Please use format.sh to format your code.
  • The code need to be well-documented to ensure future contributors can easily understand the code.
  • Include sufficient tests to ensure the project to stay correct and robust. This includes both unit tests and integration tests.
  • Please add documentation to docs/source/ if the PR modifies the user-facing behaviors of vLLM. It helps vLLM user understand and utilize the new features or changes.

Notes for Large Changes

Please keep the changes as concise as possible. For major architectural changes (>500 LOC excluding kernel/data/config/test), we would expect a GitHub issue (RFC) discussing the technical design and justification. Otherwise, we will tag it with rfc-required and might not go through the PR.

What to Expect for the Reviews

The goal of the vLLM team is to be a transparent reviewing machine. We would like to make the review process transparent and efficient and make sure no contributor feel confused or frustrated. However, the vLLM team is small, so we need to prioritize some PRs over others. Here is what you can expect from the review process:

  • After the PR is submitted, the PR will be assigned to a reviewer. Every reviewer will pick up the PRs based on their expertise and availability.
  • After the PR is assigned, the reviewer will provide status update every 2-3 days. If the PR is not reviewed within 7 days, please feel free to ping the reviewer or the vLLM team.
  • After the review, the reviewer will put an action-required label on the PR if there are changes required. The contributor should address the comments and ping the reviewer to re-review the PR.
  • Please respond to all comments within a reasonable time frame. If a comment isn't clear or you disagree with a suggestion, feel free to ask for clarification or discuss the suggestion.

Thank You

Finally, thank you for taking the time to read these guidelines and for your interest in contributing to vLLM. Your contributions make vLLM a great tool for everyone!

Isotr0py avatar Jun 02 '24 06:06 Isotr0py

Hi @Isotr0py, I can help with this PR if needed. I've already done some work implementing all GGUF quants + related kernels in vLLM. Let me know if you'd like to collaborate on this!

AlpinDale avatar Jun 02 '24 09:06 AlpinDale

@AlpinDale Thanks! I'm glad to push this forward by adding quants kernels!

I'm not familiar with the quantization in ggml and it's difficult for me to implement the mmq/mmvq ops.

And about this, I have several questions/ideas about the kernel implements:

  1. Can we also implement CPU quants kernel besides CUDA kernel? So that CPU backend can also take advantage from this.
  2. Can we get potential performance improvement by implementing the kernel with Triton?

Isotr0py avatar Jun 03 '24 08:06 Isotr0py

Great job @Isotr0py, sorry I was away for a while.

Would it be better to directly port the dequantization kernels to vLLM instead of relying on the transformers integration? They seem to have only the simple quants, and I don't imagine they're very performant. Aphrodite Engine already implements GGUF loading, so we can pull the kernels directly here if needed. Please see here for the kernels, and here for the GGUF linear method. One of the biggest problems I've had with GGUF (and exllamav2) are the quantized embeddings. If we can find an elegant solution to that, it'd do us a lot of good. GGUF quantizes both input and output embeddings, I believe. For that, please check out the linear.py and the vocab_parallel_embedding.py.

Let me know how I can help with the integration. Cheers!

AlpinDale avatar Jun 14 '24 01:06 AlpinDale

@AlpinDale I agree that we can directly port the Aphrodite Engine's dequantization kernels to vLLM. But I think we can also keep the transformers integration dequantization for CPU backend until we add the optimized kernel for CPU. (If I haven't missed something, Aphrodite Engine should only have CUDA kernels implemented for GGUF, right?)

IMO, I think vocab_parallel_embedding.py in Aphrodite Engine has been a good enough solution for quantized embeddings.

I also wonder if we can optimize the kernel's ops for merged linear, because we need to unpack the quantized weights in merged linear layer, collect and re-pack the outputs currently. (If this can be solved, we can support many models without modifying their implementation!)

(I will update this PR once I finish the work in another PR.)

Isotr0py avatar Jun 14 '24 15:06 Isotr0py

Yeah, the kernels are CUDA only (and they don't work with ROCm for now). It'd be exciting if this PR can be merged with the proper dequant kernels, so I can switch over my implementation to this too. GGUF in particular has made catching up with vLLM upstream a nightmare for me :)

Are you on slack or discord? We can discuss this in further depth if you'd like.

AlpinDale avatar Jun 14 '24 16:06 AlpinDale

@AlpinDale I think we can discuss this further on discord. How I can communicate with you on discord?

Isotr0py avatar Jun 17 '24 07:06 Isotr0py

My username is alpindale

AlpinDale avatar Jun 17 '24 07:06 AlpinDale

Currently, install gguf from pypi will only get gguf=0.6.0 which is an old version months ago. However, to use imatrix quantization, it requires newest version which need to install from source:

git clone https://github.com/ggerganov/llama.cpp
cd llama.cpp/gguf-py

pip install --editable .

Isotr0py avatar Jul 08 '24 09:07 Isotr0py

As discussed privately with @Isotr0py it may be best if we shipped a custom, up-to-date gguf utility library. Currently, aphrodite directly bundles the code, we can get away with it because the only requirement is numpy. This may be undesirable for vLLM, so perhaps the maintainers would be willing to host a custom gguf package like with flash attention?

AlpinDale avatar Jul 08 '24 09:07 AlpinDale

@Isotr0py @AlpinDale Do you know why the package is not kept up to date? It seems like updating it is a simple workflow present in llama.cpp https://github.com/ggerganov/llama.cpp/blob/c4dd11d1d3903e1922c06242e189f6310fc4d8c3/.github/workflows/gguf-publish.yml

It would be best if we could get the llama.cpp project to update this package. I couldn't find a discussion about why this hasn't been updated this year.

EDIT: I found this, someone said they are looking into it 2 days ago! https://github.com/ggerganov/llama.cpp/discussions/8272 From the above discussion, it is clear that transformers relies on the pypi package as well so I would prefer to follow their lead: https://github.com/huggingface/transformers/blob/594c1610fa6243b2ffb670c49faf389ca5121939/docker/transformers-quantization-latest-gpu/Dockerfile#L51-L52

mgoin avatar Jul 08 '24 18:07 mgoin

@Isotr0py They fixed it! Please try the new gguf==0.9.1 release https://pypi.org/project/gguf/

mgoin avatar Jul 10 '24 13:07 mgoin

Nice! I will check it out and add test for qwen2 and imatrix!

Isotr0py avatar Jul 10 '24 13:07 Isotr0py

@mgoin Could you please take a look at this once again?

The way to handle get_quant_method for vocal embedding is confusing me. Could you give some suggestions about this?

Thanks!

Isotr0py avatar Jul 28 '24 17:07 Isotr0py

@Isotr0py I started looking at this and saw your issue. I decided it would be best for quantize methods to just allow for running as if they are linear methods with apply, or as embeddings with embedding. I'll be pushing up a new state to this PR.

class QuantizeMethodBase(ABC):
    """Base class for different quantized methods."""

    @abstractmethod
    def create_weights(self, layer: torch.nn.Module, *weight_args,
                       **extra_weight_attrs):
        """Create weights for a layer.

        The weights will be set as attributes of the layer."""
        raise NotImplementedError

    @abstractmethod
    def apply(self, layer: torch.nn.Module, *args, **kwargs) -> torch.Tensor:
        """Apply the weights in layer to the input tensor.

        Expects create_weights to have been called before on the layer."""
        raise NotImplementedError

    # Not required functions
    def embedding(self, layer: torch.nn.Module, *args,
                  **kwargs) -> torch.Tensor:
        """Gather embeddings in the layer based on indices in the input tensor.
        
        Expects create_weights to have been called before on the layer."""
        raise NotImplementedError

    def process_weights_after_loading(self, layer: nn.Module) -> None:
        """Process the weight after loading.

        This can be used for example, to transpose weights for computation.
        """
        return

mgoin avatar Jul 31 '24 17:07 mgoin

The tensor parallelism hasn't worked yet, because we haven't considered the distributed situation with tp_size and tp_rank when modifying weight_loader for gguf quantization.

I will try to fix the tensor parallelism later.

Isotr0py avatar Aug 01 '24 14:08 Isotr0py

@Isotr0py I think you can work on TP in another PR, not required to land. But we should have a specific check + exception in the quantization config, rather than allowing it to fail during weight loading

mgoin avatar Aug 01 '24 14:08 mgoin

OK, I have added a check to raise exception for tp_size>1 when initialize GGUFConfig.

Isotr0py avatar Aug 01 '24 14:08 Isotr0py

Thanks for the nice work @Isotr0py and @AlpinDale - let's keep it up with improvements!

mgoin avatar Aug 06 '24 00:08 mgoin

Nice update. I was wondering how I can load my .gguf model directly from my local directory with this new update.

# Initialize the model
model_path = "/content/qwen1_5-0_5b-chat-q2_k.gguf"
llm = LLM(model=model_path)

sampling_params = SamplingParams(temperature=0.5, max_tokens=200)
prompt = "How many helicopters can a human eat in one sitting?"
response = llm.generate(prompt, sampling_params)
output_tokens = len(response[0].outputs[0].token_ids)

generated_text = response[0].outputs[0].text
print(generated_text)

Error: OSError: It looks like the config file at '/content/qwen1_5-0_5b-chat-q2_k.gguf' is not a valid JSON file.

Thanks

inuwamobarak avatar Aug 06 '24 19:08 inuwamobarak

testing this file https://github.com/vllm-project/vllm/blob/main/examples/gguf_inference.py also gave a similar issue:

OSError: It looks like the config file at '/root/.cache/huggingface/hub/models--TheBloke--TinyLlama-1.1B-Chat-v1.0-GGUF/snapshots/52e7645ba7c309695bec7ac98f4f005b139cf465/tinyllama-1.1b-chat-v1.0.Q4_0.gguf' is not a valid JSON file.

inuwamobarak avatar Aug 06 '24 19:08 inuwamobarak

@inuwamobarak I have the same message

kalebeasilvadev avatar Aug 06 '24 19:08 kalebeasilvadev

Yes @kalebeasilvadev I prefer to load my model locally as .gguf file but it seems not to work.

I saw this commit from June but it gave the same JSON error too:

from vllm import LLM, SamplingParams

# Sample prompts.
prompts = [
    "Hello, my name is",
]
# Create a sampling params object.
sampling_params = SamplingParams(temperature=0.8, top_p=0.95)

# Create an LLM.
llm = LLM(
    model="/content/tinyllama-1.1b-chat-v0.3.Q2_K.gguf",
    tokenizer="TinyLlama/TinyLlama-1.1B-Chat-v1.0",
    load_format="gguf"
)
# Generate texts from the prompts. The output is a list of RequestOutput objects
# that contain the prompt, generated text, and other information.
outputs = llm.generate(prompts, sampling_params)
# Print the outputs.
for output in outputs:
    prompt = output.prompt
    generated_text = output.outputs[0].text
    print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}")

OSError: It looks like the config file at '/content/tinyllama-1.1b-chat-v0.3.Q2_K.gguf' is not a valid JSON file.

inuwamobarak avatar Aug 06 '24 23:08 inuwamobarak

@inuwamobarak @kalebeasilvadev This model works fine from my testing just now. I am able to spin up a vLLM server:

wget https://huggingface.co/TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF/resolve/main/tinyllama-1.1b-chat-v1.0.Q2_K.gguf
vllm serve tinyllama-1.1b-chat-v1.0.Q2_K.gguf --tokenizer TinyLlama/TinyLlama-1.1B-Chat-v1.0

Are you building from source or using the nightly build? This feature is not in a release yet, it didn't make it in 0.5.4 as you can see in the release notes.

If you want to try the GGUF support you must build main from source or use the nightly build:

export VLLM_VERSION=0.5.4 # vLLM's main branch version is currently set to latest released tag
pip install https://vllm-wheels.s3.us-west-2.amazonaws.com/nightly/vllm-${VLLM_VERSION}-cp38-abi3-manylinux1_x86_64.whl
# You can also access a specific commit
# export VLLM_COMMIT=fd95e026e0f9f50bacf1a63ef419df8bacfc99c0
# pip install https://vllm-wheels.s3.us-west-2.amazonaws.com/${VLLM_COMMIT}/vllm-${VLLM_VERSION}-cp38-abi3-manylinux1_x86_64.whl

mgoin avatar Aug 06 '24 23:08 mgoin

@Isotr0py I found one problem when loading some GGUF versions of Llama 3.1. Looks like that RoPE weights in the GGUF model don't have a conversion to the HF model.

I changed the code from the function "gguf_quant_weights_iterator" to remove this weight and after that the LLM load and run worked:

    for tensor in reader.tensors:
        if(tensor.name != "rope_freqs.weight"):
            weight_type = tensor.tensor_type
            name = gguf_to_hf_name_map[tensor.name]

            if weight_type.name != "F32":
                weight_type_name = name.replace("weight", "qweight_type")
                weight_type = torch.tensor(weight_type)
                yield weight_type_name, weight_type

    for tensor in reader.tensors:
        if(tensor.name != "rope_freqs.weight"):
            weight = tensor.data
            weight_type = tensor.tensor_type
            name = gguf_to_hf_name_map[tensor.name]

            if weight_type.name != "F32":
                name = name.replace("weight", "qweight")
            param = torch.tensor(weight)
            yield name, param

I'm not a specialist in LLM architecture and don't know if this can impact the results, could you evaluate if what I did makes sense?

vbiral avatar Aug 07 '24 07:08 vbiral

@inuwamobarak @kalebeasilvadev This model works fine from my testing just now. I am able to spin up a vLLM server:

wget https://huggingface.co/TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF/resolve/main/tinyllama-1.1b-chat-v1.0.Q2_K.gguf
vllm serve tinyllama-1.1b-chat-v1.0.Q2_K.gguf --tokenizer TinyLlama/TinyLlama-1.1B-Chat-v1.0

Are you building from source or using the nightly build? This feature is not in a release yet, it didn't make it in 0.5.4 as you can see in the release notes.

If you want to try the GGUF support you must build main from source or use the nightly build:

export VLLM_VERSION=0.5.4 # vLLM's main branch version is currently set to latest released tag
pip install https://vllm-wheels.s3.us-west-2.amazonaws.com/nightly/vllm-${VLLM_VERSION}-cp38-abi3-manylinux1_x86_64.whl
# You can also access a specific commit
# export VLLM_COMMIT=fd95e026e0f9f50bacf1a63ef419df8bacfc99c0
# pip install https://vllm-wheels.s3.us-west-2.amazonaws.com/${VLLM_COMMIT}/vllm-${VLLM_VERSION}-cp38-abi3-manylinux1_x86_64.whl

Thank you @mgoin it worked now

inuwamobarak avatar Aug 07 '24 07:08 inuwamobarak

@vbiral Thanks for reporting! Seems that the gguf_to_hf_name_map didn't handle rope_freqs correctly. I will have a look and fix it.

Isotr0py avatar Aug 07 '24 12:08 Isotr0py

Yeah, the kernels are CUDA only (and they don't work with ROCm for now). It'd be exciting if this PR can be merged with the proper dequant kernels, so I can switch over my implementation to this too. GGUF in particular has made catching up with vLLM upstream a nightmare for me :)

Are you on slack or discord? We can discuss this in further depth if you'd like.

Has the kernels been verified with ROCm in MI30X machines ? Better to have a micro benchmark datasheet.