base_model: ibm-granite/granite-3.0-3b-a800m-instruct frameworks:
- PyTorch library_name: openmind license: apache-2.0 pipeline_tag: text-generation tags:
- language
- granite-3.0 quantized_by: bartowski inference: false model-index:
- name: granite-3.0-2b-instruct
results:
- task:
type: text-generation
dataset:
name: IFEval
type: instruction-following
metrics:
- type: pass@1 value: 42.49 name: pass@1
- type: pass@1 value: 7.02 name: pass@1
- task:
type: text-generation
dataset:
name: AGI-Eval
type: human-exams
metrics:
- type: pass@1 value: 25.7 name: pass@1
- type: pass@1 value: 50.16 name: pass@1
- type: pass@1 value: 20.51 name: pass@1
- task:
type: text-generation
dataset:
name: OBQA
type: commonsense
metrics:
- type: pass@1 value: 40.8 name: pass@1
- type: pass@1 value: 59.95 name: pass@1
- type: pass@1 value: 71.86 name: pass@1
- type: pass@1 value: 67.01 name: pass@1
- type: pass@1 value: 48.0 name: pass@1
- task:
type: text-generation
dataset:
name: BoolQ
type: reading-comprehension
metrics:
- type: pass@1 value: 78.65 name: pass@1
- type: pass@1 value: 6.71 name: pass@1
- task:
type: text-generation
dataset:
name: ARC-C
type: reasoning
metrics:
- type: pass@1 value: 50.94 name: pass@1
- type: pass@1 value: 26.85 name: pass@1
- type: pass@1 value: 37.7 name: pass@1
- task:
type: text-generation
dataset:
name: HumanEvalSynthesis
type: code
metrics:
- type: pass@1 value: 39.63 name: pass@1
- type: pass@1 value: 40.85 name: pass@1
- type: pass@1 value: 35.98 name: pass@1
- type: pass@1 value: 27.4 name: pass@1
- task:
type: text-generation
dataset:
name: GSM8K
type: math
metrics:
- type: pass@1 value: 47.54 name: pass@1
- type: pass@1 value: 19.86 name: pass@1
- task:
type: text-generation
dataset:
name: PAWS-X (7 langs)
type: multilingual
metrics:
- type: pass@1 value: 50.23 name: pass@1
- type: pass@1 value: 28.87 name: pass@1
- task:
type: text-generation
dataset:
name: IFEval
type: instruction-following
metrics:
Llamacpp imatrix Quantizations of granite-3.0-3b-a800m-instruct
Using llama.cpp release b3930 for quantization.
Original model: https://huggingface.co/ibm-granite/granite-3.0-3b-a800m-instruct
All quants made using imatrix option with dataset from here
Run them in LM Studio
Prompt format
<|start_of_role|>system<|end_of_role|>{system_prompt}<|end_of_text|>
<|start_of_role|>user<|end_of_role|>{prompt}<|end_of_text|>
<|start_of_role|>assistant<|end_of_role|>
Use in openmind
Note: Currently trans doesn't support loading granitemoe related models, writing them manually can load them, but there may be problems with the tokenizer.
import os
import time
import argparse
import torch
from torch import nn
import numpy as np
import logging
from transformers.integrations import GGUF_TENSOR_MAPPING, GGUF_CONFIG_MAPPING
from transformers.modeling_gguf_pytorch_utils import GGUF_TO_TRANSFORMERS_MAPPING, GGUF_SUPPORTED_ARCHITECTURES
from transformers.integrations.ggml import GGUF_TO_FAST_CONVERTERS, GGUFGPTConverter
model_type = "granitemoe"
GGUF_TENSOR_MAPPING.update(
{
model_type: {
"token_embd": "model.embed_tokens",
"blk": "model.layers",
"ffn_gate_exps": "block_sparse_moe.gate_linear",
"ffn_up_exps": "block_sparse_moe.input_linear",
"ffn_down_exps": "block_sparse_moe.output_linear",
"ffn_gate_inp": "block_sparse_moe.router.layer",
"ffn_norm": "post_attention_layernorm",
"attn_norm": "input_layernorm",
"attn_q": "self_attn.q_proj",
"attn_v": "self_attn.v_proj",
"attn_k": "self_attn.k_proj",
"attn_output": "self_attn.o_proj",
"output.weight": "lm_head.weight",
"output_norm": "model.norm",
}
}
)
GGUF_CONFIG_MAPPING.update(
{
model_type: {
"block_count": "num_hidden_layers",
"context_length": "max_position_embeddings",
"embedding_length": "hidden_size",
"feed_forward_length": "intermediate_size",
"attention.head_count": "num_attention_heads",
"attention.head_count_kv": "num_key_value_heads",
"rope.freq_base": "rope_theta",
"attention.layer_norm_rms_epsilon": "rms_norm_eps",
"expert_count": "num_local_experts",
"expert_used_count": "num_experts_per_tok",
"vocab_size": "vocab_size",
"rope.dimension_count": None,
},
}
)
GGUF_TO_TRANSFORMERS_MAPPING.update(
{
"config": GGUF_CONFIG_MAPPING,
"tensors": GGUF_TENSOR_MAPPING,
}
)
GGUF_SUPPORTED_ARCHITECTURES.append(model_type)
GGUF_TO_FAST_CONVERTERS.update(
{
model_type: GGUFGPTConverter,
}
)
# 修改 transformers 包中的 GraniteMoeMoE 类
def modify_granitemoe():
import transformers.models.granitemoe.modeling_granitemoe as granitemoe
class ModifiedGraniteMoeMoE(nn.Module):
def __init__(self, config: granitemoe.GraniteMoeConfig):
super(ModifiedGraniteMoeMoE, self).__init__()
self.input_size = config.hidden_size
self.hidden_size = config.intermediate_size
self.activation = granitemoe.ACT2FN[config.hidden_act]
self.gate_linear = granitemoe.GraniteMoeParallelExperts(config.num_local_experts, self.input_size, self.hidden_size)
self.input_linear = granitemoe.GraniteMoeParallelExperts(config.num_local_experts, self.input_size, self.hidden_size)
self.output_linear = granitemoe.GraniteMoeParallelExperts(config.num_local_experts, self.hidden_size, self.input_size)
self.router = granitemoe.GraniteMoeTopKGating(
input_size=self.input_size,
num_experts=config.num_local_experts,
top_k=config.num_experts_per_tok,
)
def forward(self, layer_input):
bsz, length, emb_size = layer_input.size()
layer_input = layer_input.reshape(-1, emb_size)
_, batch_index, batch_gates, expert_size, router_logits = self.router(layer_input)
expert_inputs = layer_input[batch_index]
hidden_states = self.activation(self.gate_linear(expert_inputs, expert_size)) * self.input_linear(expert_inputs, expert_size)
expert_outputs = self.output_linear(hidden_states, expert_size)
expert_outputs = expert_outputs * batch_gates[:, None]
zeros = torch.zeros((bsz * length, self.input_size), dtype=expert_outputs.dtype, device=expert_outputs.device)
layer_output = zeros.index_add(0, batch_index, expert_outputs)
layer_output = layer_output.view(bsz, length, self.input_size)
return layer_output, router_logits
granitemoe.GraniteMoeMoE = ModifiedGraniteMoeMoE
# 在导入 transformers 之前调用修改函数
modify_granitemoe()
# ------------------------------------------------
def parse_args():
parser = argparse.ArgumentParser(description="NPU Inference for Text Generation Model")
parser.add_argument(
"--model_name_or_path",
"-m",
type=str,
help="Path to model",
default=".",
)
parser.add_argument(
"--inference_mode",
"-i",
type=str,
help="Inference mode",
default="gguf",
)
parser.add_argument(
"--gguf_file",
"-g",
type=str,
help="Path to GGUF file",
default="granite-3.0-3b-a800m-instruct-Q4_0.gguf",
)
parser.add_argument(
"--debug",
action="store_true",
help="Debug mode",
)
return parser.parse_args()
def set_logging(model_name):
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
handlers=[
logging.FileHandler(f"{model_name}_inference.log"),
logging.StreamHandler(),
],
)
args = parse_args()
set_logging(os.path.basename(args.model_name_or_path))
if args.debug:
logging.info("Debug mode enabled, using transformers package from source.")
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline, is_torch_npu_available
else:
logging.info("Debug mode disabled, using openmind package.")
from openmind import AutoTokenizer, AutoModelForCausalLM, pipeline, is_torch_npu_available
def load_model_from_gguf(model_path: str, device_map="auto"):
gguf_filename = args.gguf_file
tokenizer = AutoTokenizer.from_pretrained(model_path, gguf_file=gguf_filename, tokenizer_type="gpt2")
tokenizer.pad_token = tokenizer.eos_token
model = AutoModelForCausalLM.from_pretrained(model_path, gguf_file=gguf_filename, device_map=device_map)
return tokenizer, model
def load_model_from_local(model_path: str, device_map="auto"):
tokenizer = AutoTokenizer.from_pretrained(model_path)
model = AutoModelForCausalLM.from_pretrained(model_path, device_map=device_map)
return tokenizer, model
def load_model_from_pipeline(model_path: str, device_map="auto", task="text-generation"):
pipeline_pt = pipeline(
task=task,
model=model_path,
device_map=device_map,
framework="pt",
truncation=True,
)
return pipeline_pt.tokenizer, pipeline_pt
def load_model(mode: str, *args, **kwargs):
if mode == "gguf":
return load_model_from_gguf(*args, **kwargs)
elif mode == "model":
return load_model_from_local(*args, **kwargs)
elif mode == "pipeline":
return load_model_from_pipeline(*args, **kwargs)
else:
raise ValueError(f"load_model Unknown mode: {mode}")
def generate_text_form_model(tokenizer, model, prompt, max_new_tokens=50):
inputs = tokenizer(prompt, return_tensors="pt", padding=True).to(model.device)
output = model.generate(
input_ids=inputs['input_ids'],
attention_mask=inputs['attention_mask'],
max_new_tokens=max_new_tokens,
)
return tokenizer.decode(output[0], skip_special_tokens=True)
def generate_text_from_pipeline(tokenizer, pipeline, prompt, max_new_tokens=50):
results = pipeline(
prompt,
max_new_tokens=max_new_tokens,
)
return results[0]["generated_text"]
def generate_text(mode: str, *args, **kwargs):
if mode == "model" or mode == "gguf":
return generate_text_form_model(*args, **kwargs)
elif mode == "pipeline":
return generate_text_from_pipeline(*args, **kwargs)
else:
raise ValueError(f"generate_text Unknown mode: {mode}")
def apply_chat_template(tokenizer, tokenize=False):
if tokenizer.chat_template is None:
print("Chat template is not defined, use default template.")
tokenizer.chat_template = "{% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}"
chat = [
{
"role": "system",
"content": "You are a helpful assistant who always responds in a friendly manner",
},
{
"role": "user",
"content": "Why does the ocean appear blue?",
},
]
chat_input = tokenizer.apply_chat_template(chat, tokenize=tokenize)
return chat_input
def main():
model_path = args.model_name_or_path
abs_model_path = os.path.abspath(model_path)
model_name = os.path.basename(abs_model_path)
logging.info(f"测试模型: {model_name}")
logging.info(f"模型路径: {model_path}")
logging.info(f"绝对路径: {abs_model_path}")
inference_mode = args.inference_mode
logging.info(f"推理模式: {inference_mode}")
# 确保使用 NPU 设备
device_map = "auto" if is_torch_npu_available() else "cpu"
logging.info(f"NPU {'available' if device_map == 'auto' else 'not available'}, use device_map='{device_map}'.")
# 加载模型
tokenizer, task_pipeline = load_model(mode=inference_mode, model_path=model_path, device_map=device_map)
prompt = apply_chat_template(tokenizer, tokenize=False)
# 推理性能测试
inference_times = []
num_runs = 10
logging.info(f"\n=== NPU {model_name} 性能测试 ===")
for i in range(num_runs):
input_text = prompt
start_time = time.time()
results = generate_text(inference_mode, tokenizer, task_pipeline, input_text)
# torch.npu.synchronize()
inference_time = time.time() - start_time
inference_times.append(inference_time)
if i == 0:
logging.info(f"输入文本: {input_text}")
logging.info("生成结果:")
logging.info(f" {results}")
avg_time = np.mean(inference_times)
std_time = np.std(inference_times)
logging.info("\n性能分析:")
logging.info(f"NPU平均推理时间: {avg_time:.4f} 秒")
logging.info(f"NPU推理时间标准差: {std_time:.4f} 秒")
logging.info(f"推理时间列表: {inference_times}")
if __name__ == "__main__":
main()
Download a file (not the whole branch) from below:
| Filename | Quant type | File Size | Split | Description |
|---|---|---|---|---|
| granite-3.0-3b-a800m-instruct-f16.gguf | f16 | 6.75GB | false | Full F16 weights. |
| granite-3.0-3b-a800m-instruct-Q8_0.gguf | Q8_0 | 3.59GB | false | Extremely high quality, generally unneeded but max available quant. |
| granite-3.0-3b-a800m-instruct-Q6_K_L.gguf | Q6_K_L | 2.81GB | false | Uses Q8_0 for embed and output weights. Very high quality, near perfect, recommended. |
| granite-3.0-3b-a800m-instruct-Q6_K.gguf | Q6_K | 2.78GB | false | Very high quality, near perfect, recommended. |
| granite-3.0-3b-a800m-instruct-Q5_K_L.gguf | Q5_K_L | 2.45GB | false | Uses Q8_0 for embed and output weights. High quality, recommended. |
| granite-3.0-3b-a800m-instruct-Q5_K_M.gguf | Q5_K_M | 2.41GB | false | High quality, recommended. |
| granite-3.0-3b-a800m-instruct-Q5_K_S.gguf | Q5_K_S | 2.34GB | false | High quality, recommended. |
| granite-3.0-3b-a800m-instruct-Q4_K_L.gguf | Q4_K_L | 2.12GB | false | Uses Q8_0 for embed and output weights. Good quality, recommended. |
| granite-3.0-3b-a800m-instruct-Q4_K_M.gguf | Q4_K_M | 2.06GB | false | Good quality, default size for must use cases, recommended. |
| granite-3.0-3b-a800m-instruct-Q4_K_S.gguf | Q4_K_S | 1.94GB | false | Slightly lower quality with more space savings, recommended. |
| granite-3.0-3b-a800m-instruct-Q4_0_8_8.gguf | Q4_0_8_8 | 1.93GB | false | Optimized for ARM inference. Requires 'sve' support (see link below). Don't use on Mac or Windows. |
| granite-3.0-3b-a800m-instruct-Q4_0_4_8.gguf | Q4_0_4_8 | 1.93GB | false | Optimized for ARM inference. Requires 'i8mm' support (see link below). Don't use on Mac or Windows. |
| granite-3.0-3b-a800m-instruct-Q4_0_4_4.gguf | Q4_0_4_4 | 1.93GB | false | Optimized for ARM inference. Should work well on all ARM chips, pick this if you're unsure. Don't use on Mac or Windows. |
| granite-3.0-3b-a800m-instruct-Q4_0.gguf | Q4_0 | 1.93GB | false | Legacy format, generally not worth using over similarly sized formats |
| granite-3.0-3b-a800m-instruct-Q3_K_XL.gguf | Q3_K_XL | 1.84GB | false | Uses Q8_0 for embed and output weights. Lower quality but usable, good for low RAM availability. |
| granite-3.0-3b-a800m-instruct-IQ4_XS.gguf | IQ4_XS | 1.82GB | false | Decent quality, smaller than Q4_K_S with similar performance, recommended. |
| granite-3.0-3b-a800m-instruct-Q3_K_L.gguf | Q3_K_L | 1.77GB | false | Lower quality but usable, good for low RAM availability. |
| granite-3.0-3b-a800m-instruct-Q3_K_M.gguf | Q3_K_M | 1.64GB | false | Low quality. |
| granite-3.0-3b-a800m-instruct-IQ3_M.gguf | IQ3_M | 1.52GB | false | Medium-low quality, new method with decent performance comparable to Q3_K_M. |
| granite-3.0-3b-a800m-instruct-Q3_K_S.gguf | Q3_K_S | 1.49GB | false | Low quality, not recommended. |
| granite-3.0-3b-a800m-instruct-IQ3_XS.gguf | IQ3_XS | 1.41GB | false | Lower quality, new method with decent performance, slightly better than Q3_K_S. |
| granite-3.0-3b-a800m-instruct-Q2_K_L.gguf | Q2_K_L | 1.34GB | false | Uses Q8_0 for embed and output weights. Very low quality but surprisingly usable. |
| granite-3.0-3b-a800m-instruct-Q2_K.gguf | Q2_K | 1.27GB | false | Very low quality but surprisingly usable. |
Embed/output weights
Some of these quants (Q3_K_XL, Q4_K_L etc) are the standard quantization method with the embeddings and output weights quantized to Q8_0 instead of what they would normally default to.
Some say that this improves the quality, others don't notice any difference. If you use these models PLEASE COMMENT with your findings. I would like feedback that these are actually used and useful so I don't keep uploading quants no one is using.
Thanks!
Downloading using huggingface-cli
First, make sure you have hugginface-cli installed:
pip install -U "huggingface_hub[cli]"
Then, you can target the specific file you want:
huggingface-cli download bartowski/granite-3.0-3b-a800m-instruct-GGUF --include "granite-3.0-3b-a800m-instruct-Q4_K_M.gguf" --local-dir ./
If the model is bigger than 50GB, it will have been split into multiple files. In order to download them all to a local folder, run:
huggingface-cli download bartowski/granite-3.0-3b-a800m-instruct-GGUF --include "granite-3.0-3b-a800m-instruct-Q8_0/*" --local-dir ./
You can either specify a new local-dir (granite-3.0-3b-a800m-instruct-Q8_0) or download them all in place (./)
Q4_0_X_X
These are NOT for Metal (Apple) offloading, only ARM chips.
If you're using an ARM chip, the Q4_0_X_X quants will have a substantial speedup. Check out Q4_0_4_4 speed comparisons on the original pull request
To check which one would work best for your ARM chip, you can check AArch64 SoC features (thanks EloyOn!).
Which file should I choose?
A great write up with charts showing various performances is provided by Artefact2 here
The first thing to figure out is how big a model you can run. To do this, you'll need to figure out how much RAM and/or VRAM you have.
If you want your model running as FAST as possible, you'll want to fit the whole thing on your GPU's VRAM. Aim for a quant with a file size 1-2GB smaller than your GPU's total VRAM.
If you want the absolute maximum quality, add both your system RAM and your GPU's VRAM together, then similarly grab a quant with a file size 1-2GB Smaller than that total.
Next, you'll need to decide if you want to use an 'I-quant' or a 'K-quant'.
If you don't want to think too much, grab one of the K-quants. These are in format 'QX_K_X', like Q5_K_M.
If you want to get more into the weeds, you can check out this extremely useful feature chart:
But basically, if you're aiming for below Q4, and you're running cuBLAS (Nvidia) or rocBLAS (AMD), you should look towards the I-quants. These are in format IQX_X, like IQ3_M. These are newer and offer better performance for their size.
These I-quants can also be used on CPU and Apple Metal, but will be slower than their K-quant equivalent, so speed vs performance is a tradeoff you'll have to decide.
The I-quants are not compatible with Vulcan, which is also AMD, so if you have an AMD card double check if you're using the rocBLAS build or the Vulcan build. At the time of writing this, LM Studio has a preview with ROCm support, and other inference engines have specific builds for ROCm.
Credits
Thank you kalomaze and Dampf for assistance in creating the imatrix calibration dataset
Thank you ZeroWw for the inspiration to experiment with embed/output
Want to support my work? Visit my ko-fi page here: https://ko-fi.com/bartowski