Returns a shallow copy of the input tree with subtrees pruned based on `should_prune`. This is a shallow copy because leaf nodes (non-dict values) are not deep-copied. Args: in_tree: The input tree to be pruned. should_prune: A callable which takes (path, subtree) as input
(
in_tree: NestedTensor,
should_prune: Callable[[str, NestedTensor], bool],
*,
prefix: str = "",
separator: str = "/",
)
| 1425 | default_dtype=param_dtype, |
| 1426 | ) |
| 1427 | # Check if param_dtype is an instance of ConfigOr[PerParamFn[jnp.dtype]] |
| 1428 | elif isinstance(param_dtype, PerParamFn) or ( |
| 1429 | isinstance(param_dtype, FunctionConfigBase) and isinstance(param_dtype.fn, PerParamFn) |
| 1430 | ): |
| 1431 | return param_dtype |
| 1432 | raise ValueError( |
| 1433 | f"{param_dtype} does not match any required types, should be " |
| 1434 | "jnp.dtype or ConfigOr[PerParamFn[jnp.dtype]]." |
| 1435 | ) |
| 1436 | |
| 1437 | |
| 1438 | def count_model_params(tree: NestedTensor) -> int: |
| 1439 | """Count the number of parameters in a model.""" |
| 1440 | return sum(x.size for x in jax.tree_util.tree_leaves(tree)) |
| 1441 | |
| 1442 | |
| 1443 | def check_param_shape_alignment( |
| 1444 | source_tree: NestedTensor, target_tree: NestedTensor |
| 1445 | ) -> Union[None, str]: |
| 1446 | """Check param shape alignment between two parameter trees. |
| 1447 | |
| 1448 | This function assumes both trees have the same structures. |
| 1449 | |
| 1450 | Args: |
| 1451 | source_tree: The source parameter tree, |
| 1452 | which can be obtained via trainer.trainer_state.model or else. |
| 1453 | target_tree: The target parameter tree, |
| 1454 | which can be obtained via trainer.trainer_state.model or else. |
| 1455 | |
| 1456 | Returns: |
| 1457 | None if shape matches. |
| 1458 | A message indicating which parameter shapes are mismatched. |
| 1459 | e.g. "(linear1/weight/0) shape is different: source: (32), target: (15)." |
| 1460 | """ |
| 1461 | param_shape_source = jax.tree.map(lambda x: x.shape, source_tree) |