KatInterview

Build a nested namespace tree from dotted model parameter names

Data Structure DesignModel answer
MediumModel answerData Structure Designstringshashingtrie

Last 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.mlp after layer1.mlp.fc1.weight, or layer01.x after layer1.x).

Analyze the time and space complexity of your solution.