Skip to content

Commit d3694f2

Browse files
authored
Merge branch 'ggml-org:master' into master
2 parents 65ac66f + a972fae commit d3694f2

39 files changed

+917
-418
lines changed

CONTRIBUTING.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@
1616
- Use the following format for the squashed commit title: `<module> : <commit title> (#<issue_number>)`. For example: `utils : fix typo in utils.py (#1234)`
1717
- Optionally pick a `<module>` from here: https://github.com/ggml-org/llama.cpp/wiki/Modules
1818
- Consider adding yourself to [CODEOWNERS](CODEOWNERS)
19+
- Let authors, who are also collaborators, merge their own PRs
20+
- When merging a PR by a contributor, make sure you have a good understanding of the changes
21+
- Be mindful of maintenance: most of the work going into a feature happens after the PR is merged. If the PR author is not committed to contribute long-term, someone else needs to take responsibility (you)
1922

2023
# Coding guidelines
2124

common/json-schema-to-grammar.cpp

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -843,9 +843,10 @@ class SchemaConverter {
843843
_build_object_rule(
844844
properties, required, name,
845845
schema.contains("additionalProperties") ? schema["additionalProperties"] : json()));
846-
} else if ((schema_type.is_null() || schema_type == "object") && schema.contains("allOf")) {
846+
} else if ((schema_type.is_null() || schema_type == "object" || schema_type == "string") && schema.contains("allOf")) {
847847
std::unordered_set<std::string> required;
848848
std::vector<std::pair<std::string, json>> properties;
849+
std::map<std::string, size_t> enum_values;
849850
std::string hybrid_name = name;
850851
std::function<void(const json &, bool)> add_component = [&](const json & comp_schema, bool is_required) {
851852
if (comp_schema.contains("$ref")) {
@@ -857,6 +858,14 @@ class SchemaConverter {
857858
required.insert(prop.key());
858859
}
859860
}
861+
} else if (comp_schema.contains("enum")) {
862+
for (const auto & v : comp_schema["enum"]) {
863+
const auto rule = _generate_constant_rule(v);
864+
if (enum_values.find(rule) == enum_values.end()) {
865+
enum_values[rule] = 0;
866+
}
867+
enum_values[rule] += 1;
868+
}
860869
} else {
861870
// todo warning
862871
}
@@ -870,6 +879,17 @@ class SchemaConverter {
870879
add_component(t, true);
871880
}
872881
}
882+
if (!enum_values.empty()) {
883+
std::vector<std::string> enum_intersection;
884+
for (const auto & p : enum_values) {
885+
if (p.second == schema["allOf"].size()) {
886+
enum_intersection.push_back(p.first);
887+
}
888+
}
889+
if (!enum_intersection.empty()) {
890+
return _add_rule(rule_name, "(" + string_join(enum_intersection, " | ") + ") space");
891+
}
892+
}
873893
return _add_rule(rule_name, _build_object_rule(properties, required, hybrid_name, json()));
874894
} else if ((schema_type.is_null() || schema_type == "array") && (schema.contains("items") || schema.contains("prefixItems"))) {
875895
json items = schema.contains("items") ? schema["items"] : schema["prefixItems"];

examples/eval-callback/eval-callback.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,15 @@ static std::string ggml_ne_string(const ggml_tensor * t) {
2828
return str;
2929
}
3030

31+
static inline float ggml_compute_bf16_to_fp32(ggml_bf16_t h) {
32+
union {
33+
float f;
34+
uint32_t i;
35+
} u;
36+
u.i = (uint32_t)h.bits << 16;
37+
return u.f;
38+
}
39+
3140
static float ggml_get_float_value(uint8_t * data, ggml_type type, const size_t * nb, size_t i0, size_t i1, size_t i2, size_t i3) {
3241
size_t i = i3 * nb[3] + i2 * nb[2] + i1 * nb[1] + i0 * nb[0];
3342
float v;
@@ -43,6 +52,8 @@ static float ggml_get_float_value(uint8_t * data, ggml_type type, const size_t *
4352
v = (float) *(int16_t *) &data[i];
4453
} else if (type == GGML_TYPE_I8) {
4554
v = (float) *(int8_t *) &data[i];
55+
} else if (type == GGML_TYPE_BF16) {
56+
v = ggml_compute_bf16_to_fp32(*(ggml_bf16_t *) &data[i]);
4657
} else {
4758
GGML_ABORT("fatal error");
4859
}

examples/json_schema_to_grammar.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -586,9 +586,10 @@ def visit(self, schema, name):
586586
properties = list(schema.get('properties', {}).items())
587587
return self._add_rule(rule_name, self._build_object_rule(properties, required, name, schema.get('additionalProperties')))
588588

589-
elif schema_type in (None, 'object') and 'allOf' in schema:
589+
elif schema_type in (None, 'object', 'string') and 'allOf' in schema:
590590
required = set()
591591
properties = []
592+
enum_sets = []
592593
hybrid_name = name
593594
def add_component(comp_schema, is_required):
594595
if (ref := comp_schema.get('$ref')) is not None:
@@ -600,13 +601,25 @@ def add_component(comp_schema, is_required):
600601
if is_required:
601602
required.add(prop_name)
602603

604+
if 'enum' in comp_schema:
605+
enum_sets.append(set(comp_schema['enum']))
606+
603607
for t in schema['allOf']:
604608
if 'anyOf' in t:
605609
for tt in t['anyOf']:
606610
add_component(tt, is_required=False)
607611
else:
608612
add_component(t, is_required=True)
609613

614+
if enum_sets:
615+
enum_intersection = enum_sets[0]
616+
for s in enum_sets[1:]:
617+
enum_intersection &= s
618+
619+
if enum_intersection:
620+
rule = '(' + ' | '.join((self._generate_constant_rule(v) for v in sorted(enum_intersection))) + ') space'
621+
return self._add_rule(rule_name, rule)
622+
610623
return self._add_rule(rule_name, self._build_object_rule(properties, required, hybrid_name, additional_properties=None))
611624

612625
elif schema_type in (None, 'array') and ('items' in schema or 'prefixItems' in schema):
Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
--extra-index-url https://download.pytorch.org/whl/cpu
2-
torch~=2.6.0
3-
torchvision~=0.21.0
4-
transformers~=4.55.0
5-
huggingface-hub~=0.34.0
2+
torch
3+
torchvision
4+
transformers
5+
huggingface-hub
6+
accelerate

examples/model-conversion/scripts/causal/run-org-model.py

Lines changed: 141 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,134 @@
99
import torch
1010
import numpy as np
1111

12-
unreleased_model_name = os.getenv('UNRELEASED_MODEL_NAME')
13-
14-
parser = argparse.ArgumentParser(description='Process model with specified path')
15-
parser.add_argument('--model-path', '-m', help='Path to the model')
12+
### If you want to dump RoPE activations, apply this monkey patch to the model
13+
### class from Transformers that you are running (replace apertus.modeling_apertus
14+
### with the proper package and class for your model
15+
### === START ROPE DEBUG ===
16+
# from transformers.models.apertus.modeling_apertus import apply_rotary_pos_emb
17+
18+
# orig_rope = apply_rotary_pos_emb
19+
# torch.set_printoptions(threshold=float('inf'))
20+
# torch.set_printoptions(precision=6, sci_mode=False)
21+
22+
# def debug_rope(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
23+
# # log inputs
24+
# summarize(q, "RoPE.q_in")
25+
# summarize(k, "RoPE.k_in")
26+
27+
# # call original
28+
# q_out, k_out = orig_rope(q, k, cos, sin, position_ids, unsqueeze_dim)
29+
30+
# # log outputs
31+
# summarize(q_out, "RoPE.q_out")
32+
# summarize(k_out, "RoPE.k_out")
33+
34+
# return q_out, k_out
35+
36+
# # Patch it
37+
# import transformers.models.apertus.modeling_apertus as apertus_mod # noqa: E402
38+
# apertus_mod.apply_rotary_pos_emb = debug_rope
39+
### == END ROPE DEBUG ===
40+
41+
42+
def summarize(tensor: torch.Tensor, name: str, max_seq: int = 3, max_vals: int = 3):
43+
"""
44+
Print a tensor in llama.cpp debug style.
45+
46+
Supports:
47+
- 2D tensors (seq, hidden)
48+
- 3D tensors (batch, seq, hidden)
49+
- 4D tensors (batch, seq, heads, dim_per_head) via flattening heads × dim_per_head
50+
51+
Shows first and last max_vals of each vector per sequence position.
52+
"""
53+
t = tensor.detach().to(torch.float32).cpu()
54+
55+
# Determine dimensions
56+
if t.ndim == 3:
57+
_, s, _ = t.shape
58+
elif t.ndim == 2:
59+
_, s = 1, t.shape[0]
60+
t = t.unsqueeze(0)
61+
elif t.ndim == 4:
62+
_, s, _, _ = t.shape
63+
else:
64+
print(f"Skipping tensor due to unsupported dimensions: {t.ndim}")
65+
return
66+
67+
ten_shape = t.shape
68+
69+
print(f"ggml_debug: {name} = (f32) ... = {{{ten_shape}}}")
70+
print(" [")
71+
print(" [")
72+
73+
# Determine indices for first and last sequences
74+
first_indices = list(range(min(s, max_seq)))
75+
last_indices = list(range(max(0, s - max_seq), s))
76+
77+
# Check if there's an overlap between first and last indices or if we're at the edge case of s = 2 * max_seq
78+
has_overlap = bool(set(first_indices) & set(last_indices)) or (max_seq * 2 == s)
79+
80+
# Combine indices
81+
if has_overlap:
82+
# If there's overlap, just use the combined unique indices
83+
indices = sorted(list(set(first_indices + last_indices)))
84+
separator_index = None
85+
else:
86+
# If no overlap, we'll add a separator between first and last sequences
87+
indices = first_indices + last_indices
88+
separator_index = len(first_indices)
89+
90+
for i, si in enumerate(indices):
91+
# Add separator if needed
92+
if separator_index is not None and i == separator_index:
93+
print(" ...")
94+
95+
# Extract appropriate slice
96+
vec = t[0, si]
97+
if vec.ndim == 2: # 4D case: flatten heads × dim_per_head
98+
flat = vec.flatten().tolist()
99+
else: # 2D or 3D case
100+
flat = vec.tolist()
101+
102+
# First and last slices
103+
first = flat[:max_vals]
104+
last = flat[-max_vals:] if len(flat) >= max_vals else flat
105+
first_str = ", ".join(f"{v:12.4f}" for v in first)
106+
last_str = ", ".join(f"{v:12.4f}" for v in last)
107+
108+
print(f" [{first_str}, ..., {last_str}]")
109+
110+
print(" ],")
111+
print(" ]")
112+
print(f" sum = {t.sum().item():.6f}\n")
113+
114+
115+
def debug_hook(name):
116+
def fn(_m, input, output):
117+
if isinstance(input, torch.Tensor):
118+
summarize(input, name + "_in")
119+
elif isinstance(input, (tuple, list)) and isinstance(input[0], torch.Tensor):
120+
summarize(input[0], name + "_in")
121+
if isinstance(output, torch.Tensor):
122+
summarize(output, name + "_out")
123+
elif isinstance(output, (tuple, list)) and isinstance(output[0], torch.Tensor):
124+
summarize(output[0], name + "_out")
125+
126+
return fn
127+
128+
129+
unreleased_model_name = os.getenv("UNRELEASED_MODEL_NAME")
130+
131+
parser = argparse.ArgumentParser(description="Process model with specified path")
132+
parser.add_argument("--model-path", "-m", help="Path to the model")
16133
args = parser.parse_args()
17134

18-
model_path = os.environ.get('MODEL_PATH', args.model_path)
135+
model_path = os.environ.get("MODEL_PATH", args.model_path)
19136
if model_path is None:
20-
parser.error("Model path must be specified either via --model-path argument or MODEL_PATH environment variable")
137+
parser.error(
138+
"Model path must be specified either via --model-path argument or MODEL_PATH environment variable"
139+
)
21140

22141
config = AutoConfig.from_pretrained(model_path)
23142

@@ -34,18 +153,30 @@
34153

35154
if unreleased_model_name:
36155
model_name_lower = unreleased_model_name.lower()
37-
unreleased_module_path = f"transformers.models.{model_name_lower}.modular_{model_name_lower}"
156+
unreleased_module_path = (
157+
f"transformers.models.{model_name_lower}.modular_{model_name_lower}"
158+
)
38159
class_name = f"{unreleased_model_name}ForCausalLM"
39160
print(f"Importing unreleased model module: {unreleased_module_path}")
40161

41162
try:
42-
model_class = getattr(importlib.import_module(unreleased_module_path), class_name)
43-
model = model_class.from_pretrained(model_path) # Note: from_pretrained, not fromPretrained
163+
model_class = getattr(
164+
importlib.import_module(unreleased_module_path), class_name
165+
)
166+
model = model_class.from_pretrained(
167+
model_path
168+
) # Note: from_pretrained, not fromPretrained
44169
except (ImportError, AttributeError) as e:
45170
print(f"Failed to import or load model: {e}")
46171
exit(1)
47172
else:
48-
model = AutoModelForCausalLM.from_pretrained(model_path)
173+
model = AutoModelForCausalLM.from_pretrained(
174+
model_path, device_map="auto", offload_folder="offload"
175+
)
176+
177+
for name, module in model.named_modules():
178+
if len(list(module.children())) == 0: # only leaf modules
179+
module.register_forward_hook(debug_hook(name))
49180

50181
model_name = os.path.basename(model_path)
51182
# Printing the Model class to allow for easier debugging. This can be useful

ggml/src/ggml-cuda/CMakeLists.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,8 @@ if (CUDAToolkit_FOUND)
6565
list(APPEND GGML_SOURCES_CUDA ${SRCS})
6666
file(GLOB SRCS "template-instances/mmq*.cu")
6767
list(APPEND GGML_SOURCES_CUDA ${SRCS})
68+
file(GLOB SRCS "template-instances/mmf*.cu")
69+
list(APPEND GGML_SOURCES_CUDA ${SRCS})
6870

6971
if (GGML_CUDA_FA_ALL_QUANTS)
7072
file(GLOB SRCS "template-instances/fattn-vec*.cu")

0 commit comments

Comments
 (0)