deeplearning4j/deeplearning4j · error · IllegalStateException

Could not resolve tensor for Merge operation

Error message

Could not resolve tensor for Merge operation %s input %s (frame=%s, iteration=%s)

What it means

During SameDiff graph execution, the InferenceSession resolved a value for an input of a Merge op (typically inside an TF-style while-loop frame/iteration), but the resulting value carried no actual INDArray tensor. The session throws IllegalStateException because Merge cannot execute without concrete tensor inputs. This indicates the upstream variable was resolved to a non-tensor value or was never materialized.

Solutions

  1. Check that every op writing into a Merge input actually produces an INDArray output (inspect ops feeding the Merge node)
  2. Verify loop-body ops write outputs for both merge branches (true and false switch paths)
  3. Ensure you are not reusing an SDVariable across frames without proper placement in the loop body
  4. Capture the execution with the visualizer (visualizationEnabled) to see which variable is unresolved at that frame/iteration
  5. Upgrade/align nd4j version: output registration behavior for control-flow frames changed between releases

Example fix

// before: loop body only assigns the 'true' branch of a switch feeding a Merge
SDVariable out = sd.switchFn(cond, x);
SDVariable mergeIn = out.get(0); // false branch never produced
// after: ensure both branches or use the merge output directly with a defined initializer
SDVariable init = sd.zerosLike(x);
SDVariable merged = sd.fwdMerge(init, out.get(0)); // both inputs always defined
Defensive patterns

Strategy: validation

Validate before calling

SDValue v = session.getSdValue(varId);
if (v == null || v.getSdValueType() != SDValueType.TENSOR || v.getTensorValue() == null)
    throw new IllegalStateException("Merge input not materialized: " + varId.getVariable());

Type guard

boolean isResolvedTensor(SDValue v) {
    return v != null && v.getSdValueType() == SDValueType.TENSOR && v.getTensorValue() != null;
}

Try / catch

try {
    sd.output(allVars, placeholders);
} catch (IllegalStateException e) {
    if (e.getMessage().contains("Could not resolve tensor for Merge")) {
        log.error("Unresolved merge input; check loop body outputs", e);
        // rebuild graph / fix loop body
    } else throw e;
}

Prevention

When it happens

Trigger: A variable feeding a Merge node was produced as an SDValue of type TENSOR whose getTensorValue() is null (e.g. the producing op placed output in a list, or getTensorFromOutputs returned null from the outputs map and no tensor was stored). Happens in while-loop execution when the merge input was never assigned in the current frame/iteration.

Common situations: Imported TensorFlow while_loop/switch-merge control-flow graphs where one branch of a switch never executes; custom loops built with SameDiff.where the loop body does not write to all merge inputs; version changes in how outputs are registered per frame/iteration.

Understand the failure class

Background: "This is a bug, please report it": internal invariant violations, unreachable panics, and SNH errors explained — this error's family across 47 libraries.

Related errors


AI-assisted analysis of deeplearning4j/deeplearning4j@4c22ac5fe4 (2026-09-07). Data as JSON: /api/errors/9381fb4d27a5d06e. Report an issue: GitHub.

Appendix: source

Thrown at nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/internal/InferenceSession.java:1753

                }

                // Use first available input (standard Merge behavior)
                SDValue selectedValue = availableValues.get(0);
                VarId selectedVarId = candidateInputs.get(0);

                log.trace("Merge {} selected input: {} from frame {}",
                        m.getOwnName(), selectedVarId.getVariable(), selectedVarId.getFrame());

                ExecutionResult result;
                if(selectedValue.getSdValueType() == SDValueType.LIST) {
                    result = ExecutionResult.createValue(selectedVarId.getVariable(), selectedValue);
                } else if(selectedValue.getSdValueType() == SDValueType.TENSOR) {
                    INDArray inArr = getTensorFromOutputs(selectedVarId);
                    if (inArr == null) {
                        inArr = selectedValue.getTensorValue();
                    }
                    if (inArr == null) {
                        throw new IllegalStateException(String.format(
                                "Could not resolve tensor for Merge operation %s input %s (frame=%s, iteration=%s)",
                                op.getOwnName(), selectedVarId.getVariable(), outputFrameIter.getFrame(), outputFrameIter.getIteration()));
                    }
                    result = ExecutionResult.createFrom(Arrays.asList(selectedVarId.getVariable()), new INDArray[]{inArr});
                } else {
                    throw new IllegalStateException("Illegal value type " + selectedValue.getSdValueType() + " for Merge input " + selectedVarId);
                }

                return result;
            }else if (op instanceof LoopCond) {
                //LoopCond just forwards scalar boolean to output
                LoopCond lc = (LoopCond) op;
                String[] argNames = lc.argNames();
                Preconditions.checkState(argNames.length == 1, "Expected only 1 arg name in LoopCond op, got %s", (Object) argNames);
                VarId vid = outputFrameIter.toVarId(argNames[0]);
                SDValue getValue = getSdValue(vid);
                if(getValue.getTensorValue() == null) {
                    throw new IllegalStateException("Node value output at " + vid.getVariable() + " was not a boolean tensor!");

View on GitHub (pinned to 4c22ac5fe4)