{"record":{"id":"a14ef2f84a5892d1","repo":"jax-ml/jax","slug":"prevent-cse-must-be-a-bool-or-tuple-of-bools-got","errorCode":null,"errorMessage":"prevent_cse must be a bool or tuple of bools, got {type(prevent_cse)=}","messagePattern":"prevent_cse must be a bool or tuple of bools, got (.+?)","errorType":"validation","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"jax/_src/ad_checkpoint.py","lineNumber":380,"sourceCode":"    @partial(jax.checkpoint, static_argnums=(1,))\n    def foo(x, y):\n      with jax.ensure_compile_time_eval():\n        y_pos = y > 0\n      if y_pos:\n        ...\n      else:\n        ...\n\n  As an alternative to using ``static_argnums`` (and\n  ``jax.ensure_compile_time_eval``), it may be easier to compute some values\n  outside the :func:`jax.checkpoint`-decorated function and then close over them.\n  \"\"\"\n  if isinstance(static_argnums, int):\n    static_argnums = static_argnums,\n  if isinstance(prevent_cse, Sequence):\n    prevent_cse = tuple(prevent_cse)\n  if not isinstance(prevent_cse, (tuple, bool)):\n    raise TypeError(\"prevent_cse must be a bool or tuple of bools, got \"\n                    f\"{type(prevent_cse)=}\")\n\n  if config.remat3.value:\n    policy = None if policy is nothing_saveable else policy\n    return remat3(fun, policy=policy, static_argnums=static_argnums,\n                  static_argnames=static_argnames, prevent_cse=prevent_cse)\n\n  @wraps(fun)\n  @api_boundary\n  def fun_remat(*args, **kwargs):\n    debug = api_util.debug_info(\n        \"checkpoint / remat\", fun,\n        args, kwargs, static_argnums=static_argnums)\n    fun_, args = _remat_static_argnums(fun, static_argnums, args)\n    args_flat, in_tree = tracing_registry.flatten((args, kwargs))\n    api_util.check_no_transformed_refs_args(lambda: debug, args_flat)\n    in_avals = [core.shaped_abstractify(x) for x in args_flat]\n    jaxpr, consts, out_tree = _trace_to_jaxpr(fun_, in_tree, tuple(in_avals), debug)","sourceCodeStart":362,"sourceCodeEnd":398,"githubUrl":"https://github.com/jax-ml/jax/blob/1e1c6a8fc06dfcd1247076ec5cae4640cea5d7bb/jax/_src/ad_checkpoint.py#L362-L398","documentation":"PyTreeDef::UnflattenImpl rebuilds a structure from a treedef and a list of leaves; when the traversal needs another leaf but the iterator is exhausted, it throws 'Too few leaves for PyTreeDef; expected %d, got %d'. num_leaves() is the treedef's expectation, leaf_count is what was supplied so far.","triggerScenarios":"Calling treedef.unflatten(leaves) or jax.tree.unflatten(treedef, leaves) with fewer leaves than treedef.num_leaves (e.g. passing a filtered or truncated leaf list, or leaves from a different treedef).","commonSituations":"Filtering leaves (e.g. dropping None or padding leaves) before unflattening; using leaves flattened under is_leaf but unflattening with the default treedef; mixing treedefs when batching/stacking params; vmap/pmap reshaping code that slices leaves.","solutions":["Check len(leaves) == treedef.num_leaves before unflattening","Flatten and unflatten with the same is_leaf predicate so treedef and leaves agree","If you intentionally dropped leaves, use treedef.replace_like / jax.tree.map(None-safe) patterns instead of filtering the leaf list","Log treedef.num_leaves vs len(leaves) at the call site when debugging"],"exampleFix":"# before\nleaves = [l for l in leaves if l is not None]\nout = treedef.unflatten(leaves)  # ValueError: too few leaves\n\n# after\nassert len(leaves) == treedef.num_leaves, (len(leaves), treedef.num_leaves)\nout = treedef.unflatten(leaves)","handlingStrategy":"validation","validationCode":"if len(leaves) != treedef.num_leaves:\n    raise ValueError(f'need {treedef.num_leaves} leaves, got {len(leaves)}')\nout = treedef.unflatten(leaves)","typeGuard":null,"tryCatchPattern":"try:\n    out = treedef.unflatten(leaves)\nexcept ValueError as e:\n    if 'Too few leaves' in str(e):\n        raise ValueError(f'leaf count mismatch: have {len(leaves)}, treedef wants {treedef.num_leaves}') from e\n    raise","preventionTips":["Always pair leaves and treedef from the same flatten call","Use the same is_leaf on flatten and unflatten paths","Assert num_leaves before unflattening in library code"],"tags":["pytree","unflatten","jax","leaf-count"],"backgroundTag":"pytree-leaf-count-mismatch","analyzedSha":"1e1c6a8fc06dfcd1247076ec5cae4640cea5d7bb","analyzedAt":"2026-08-27T09:53:25.647Z","schemaVersion":2},"datasetVersion":"2026-08-27T13:17:12.746Z"}