Build a nested namespace tree from dotted model parameter names
Data Structure DesignModel answerLast updated
Convert a flat list of dotted parameter keys like layer indices into a grouped nested dictionary, collecting nonconforming, duplicate, and structurally conflicting keys separately.
You are building a utility for a model-loading pipeline. Model parameters arrive as a flat list of dotted key strings, for example:
["layer1.attention.q_proj.weight", "layer1.attention.k_proj.weight",
"layer1.mlp.fc1.weight", "layer2.mlp.fc1.weight", ...]
Write a Python function that reorganizes these keys into a nested dictionary grouped by layer index, so that keys sharing the same component sub-path live under the same subtree. For instance, every layer{n}.attention.* key should appear under the attention subtree of layer n.
Define your own grouping rule. A reasonable approach: treat any key matching layer{n}.rest as belonging to layer n, then split rest on . to build the nested structure beneath that layer.
Handle messy input explicitly. Not every key will conform. Your function should never raise on bad input. Instead, return a result object with four fields:
layers— a dict mapping layer index (as an int) to a nested dict of component paths; leaves store the original key string.ungrouped— any key that does not match the grouping rule, including non-string items.duplicates— keys that appear more than once after the first occurrence.conflicts— keys whose insertion would collide with an existing leaf or subtree (e.g.,layer1.mlpafterlayer1.mlp.fc1.weight, orlayer01.xafterlayer1.x).
Analyze the time and space complexity of your solution.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
A strong answer first pins down the contract, then builds a trie-like structure, and handles messy input deliberately rather than letting it crash.
Defining the contract
A key is conforming if it matches ^layer(\d+)\.(.+)$ and the remainder splits on . into non-empty segments. The captured integer is the layer index; the remainder is the component path that gets nested.
The function returns a dict with four fields:
{
"layers": {int: {nested component dicts}},
"ungrouped": [...], # keys not matching the rule or non-string
"duplicates": [...], # repeated occurrences after the first
"conflicts": [...], # path collides with an existing leaf or subtree
}
Key design choices to state explicitly:
- Layer indices are stored as ints so they sort numerically.
- Leaves store the original key string so the tree maps back to a state_dict.
- Bad input never raises; everything goes into its own bucket.
Approach
Treat each component path as a trie rooted at its layer index. For every key:
- Skip non-strings and exact duplicates early (O(1) via a
seenset). - Parse with the regex; reject non-matching or empty-segment keys.
- Walk or create nested dicts for every segment except the last using
setdefault. - Place the leaf at the last segment; if the slot is already occupied or a mid-walk node is not a dict, record a conflict.
A structural conflict arises when a node must be both a leaf and a subtree, e.g. layer1.mlp after layer1.mlp.fc1.weight. Detect this in two spots: when setdefault returns a non-dict during traversal, and when the leaf slot is already filled. Leading-zero variants like layer01.x and layer1.x both map to layer 1 at the same path, so the second lands in conflicts.
Solution
import re
from typing import Any, Dict, Iterable, List
_LAYER_RE = re.compile(r"^layer(\d+)\.(.+)$")
def build_param_tree(keys: Iterable[Any]) -> Dict[str, Any]:
"""Group flat 'layer{n}.a.b.c' keys into {n: {'a': {'b': {'c': key}}}}.
Returns a dict with:
layers -> {layer_index (int): nested dict of component paths}
ungrouped -> keys not matching 'layer{n}.(.)*'
duplicates -> repeated keys (each extra occurrence listed once per repeat)
conflicts -> keys whose path collides with an existing leaf or subtree
"""
layers: Dict[int, Dict[str, Any]] = {}
ungrouped: List[Any] = []
duplicates: List[str] = []
conflicts: List[str] = []
seen = set()
for key in keys:
if not isinstance(key, str):
ungrouped.append(key)
continue
if key in seen:
duplicates.append(key)
continue
seen.add(key)
m = _LAYER_RE.match(key)
if not m:
ungrouped.append(key)
continue
parts = m.group(2).split(".")
if any(p == "" for p in parts): # catches 'layer1..w' or trailing dots
ungrouped.append(key)
continue
node = layers.setdefault(int(m.group(1)), {})
ok = True
for seg in parts[:-1]:
child = node.setdefault(seg, {})
if not isinstance(child, dict): # existing leaf blocks this path
ok = False
break
node = child
leaf = parts[-1]
if ok and leaf not in node:
node[leaf] = key
else:
conflicts.append(key)
return {
"layers": dict(sorted(layers.items())),
"ungrouped": ungrouped,
"duplicates": duplicates,
"conflicts": conflicts,
}
Why it is correct
- Every key lands in exactly one bucket. The checks run in fixed order: non-string, duplicate, nonconforming, then insert-or-conflict. Each branch continues or terminates, so nothing is lost or double-counted.
- Shared prefixes reuse existing dicts via
setdefault, solayer1.attention.q_proj.weightandlayer1.attention.k_proj.weightshare theattentionsubtree. - Conflicts leave no partial garbage. A conflict can only happen at a node that already existed, so a rejected key never creates dangling empty dicts.
- First occurrence wins, which is deterministic and easy to document. Last-wins or raise-on-conflict are one-line changes if the interviewer prefers.
Complexity
Let N be the number of keys, L the average key length, and K the number of distinct layers.
- Time: O(N·L + K log K). Regex match, split, and hashing are each linear in key length. The trie walk is O(segments) which is at most O(L). Sorting layers adds O(K log K), usually dominated by N·L since K ≤ N.
- Space: O(N·L). The
seenset stores every unique key; the trie has at most one node per segment per key, though shared prefixes reduce the real cost well below the worst case.
Edge cases to mention
| Input | Behavior |
|---|---|
| Empty list | All four collections empty |
embed.weight, lm_head.weight, layerX.foo | ungrouped |
layer1 or layer1. (no component) | ungrouped (regex needs .+) |
layer1..weight (empty segment) | ungrouped |
| Exact repeat of a conforming key | duplicates, tree unchanged |
layer1.mlp + layer1.mlp.fc1.weight (either order) | Second key goes to conflicts |
layer01.x + layer1.x | Same layer 1; second goes to conflicts |
layer10 vs layer2 | Ordered numerically: 2, then 10 |
| Non-string items (None, int) | ungrouped |