Skip to content

PanSeg CNN Prediction

panseg.functionals.prediction.prediction.unet_prediction(raw: np.ndarray, input_layout: ImageLayout, model_name: str | None, model_id: str | None, patch: tuple[int, int, int] | None = None, patch_halo: tuple[int, int, int] | None = None, single_batch_mode: bool = True, device: str = 'cuda', model_update: bool = False, disable_tqdm: bool = False, config_path: Path | None = None, model_weights_path: Path | None = None, tracker=None, amp: AmpSetting = 'auto', channels_last_3d: bool = False) -> np.ndarray

Generate prediction from raw data using a specified 3D U-Net model.

This function handles both single and multi-channel outputs from the model, returning appropriately shaped arrays based on the output channel configuration. The raw volume is reflect-padded up to the aligned domain and the prediction is cropped back, so the returned shape always equals the input shape.

For Bioimage.IO Model Zoo models, weights are downloaded and loaded into UNet3D or UNet2D in panseg.functionals.training.model, i.e. bioimageio.core is not used. biio_prediction() uses bioimageio.core for loading and running models.

Parameters:

  • raw (ndarray) –

    Raw input data.

  • Input_layout (ImageLayout) –

    The layout of the input data.

  • model_name (str | None) –

    The name of the model to use.

  • model_id (str | None) –

    The ID of the model from the BioImage.IO model zoo.

  • patch (tuple[int, int, int] | None, default: None ) –

    Patch size for prediction. None derives a patch aligned to geometry.increment and sized so patch + 2 * halo fits the probed model-input budget. Defaults to None.

  • patch_halo (tuple[int, int, int] | None, default: None ) –

    Halo size around patches. None uses geometry.halo, the minimal halo that makes an aligned patch exact; a manual halo is used verbatim (no rounding, no alignment check). Defaults to None.

  • single_batch_mode (bool, default: True ) –

    Whether to use a single batch for prediction. Defaults to True.

  • device (str, default: 'cuda' ) –

    The computation device ('cpu', 'cuda', etc.). Defaults to 'cuda'.

  • model_update (bool, default: False ) –

    Whether to update the model to the latest version. Defaults to False.

  • disable_tqdm (bool, default: False ) –

    If True, disables the tqdm progress bar. Defaults to False.

  • config_path (Path | None, default: None ) –

    Path to the model configuration file. Defaults to None.

  • model_weights_path (Path | None, default: None ) –

    Path to the model weights file. Defaults to None.

  • amp (AmpSetting, default: 'auto' ) –

    precision mode ("auto": bf16 autocast on supported CUDA devices, else fp32; "off": always fp32; the YAML-boolean spellings of these names also resolve, see validate_amp). The memory probes size patches in the same mode. Outputs are fp32 in either mode. Defaults to "auto".

  • channels_last_3d (bool, default: False ) –

    opt in to running 3D models on CUDA in the channels_last_3d memory format (kept off on CPU and for 2D models). The memory probes size patches in the same layout. Outputs are unaffected. Defaults to False.

Returns:

  • ndarray –

    np.ndarray: The predicted boundaries as a 3D (Z, Y, X) or 4D (C, Z, Y, X) array, normalized between 0 and 1.

Raises:

  • ValueError –

    If neither model_name, model_id, nor config_path are provided.

  • ValueError –

    If the patch or halo shape cannot run on the model.

Source code in panseg/functionals/prediction/prediction.py
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
def unet_prediction(
    raw: np.ndarray,
    input_layout: ImageLayout,
    model_name: str | None,
    model_id: str | None,
    patch: tuple[int, int, int] | None = None,
    patch_halo: tuple[int, int, int] | None = None,
    single_batch_mode: bool = True,
    device: str = "cuda",
    model_update: bool = False,
    disable_tqdm: bool = False,
    config_path: Path | None = None,
    model_weights_path: Path | None = None,
    tracker=None,
    amp: AmpSetting = "auto",
    channels_last_3d: bool = False,
) -> np.ndarray:
    """Generate prediction from raw data using a specified 3D U-Net model.

    This function handles both single and multi-channel outputs from the model,
    returning appropriately shaped arrays based on the output channel configuration.
    The raw volume is reflect-padded up to the aligned domain and the prediction
    is cropped back, so the returned shape always equals the input shape.

    For Bioimage.IO Model Zoo models, weights are downloaded and loaded into `UNet3D` or `UNet2D`
    in `panseg.functionals.training.model`, i.e. `bioimageio.core` is not used. `biio_prediction()` uses
    `bioimageio.core` for loading and running models.

    Args:
        raw (np.ndarray): Raw input data.
        Input_layout (ImageLayout): The layout of the input data.
        model_name (str | None): The name of the model to use.
        model_id (str | None): The ID of the model from the BioImage.IO model zoo.
        patch (tuple[int, int, int] | None, optional): Patch size for prediction.
            `None` derives a patch aligned to `geometry.increment` and sized so
            `patch + 2 * halo` fits the probed model-input budget. Defaults to None.
        patch_halo (tuple[int, int, int] | None, optional): Halo size around patches.
            `None` uses `geometry.halo`, the minimal halo that makes an aligned patch
            exact; a manual halo is used verbatim (no rounding, no alignment check).
            Defaults to None.
        single_batch_mode (bool, optional): Whether to use a single batch for prediction. Defaults to True.
        device (str, optional): The computation device ('cpu', 'cuda', etc.). Defaults to 'cuda'.
        model_update (bool, optional): Whether to update the model to the latest version. Defaults to False.
        disable_tqdm (bool, optional): If True, disables the tqdm progress bar. Defaults to False.
        config_path (Path | None, optional): Path to the model configuration file. Defaults to None.
        model_weights_path (Path | None, optional): Path to the model weights file. Defaults to None.
        amp (AmpSetting, optional): precision mode (``"auto"``: bf16 autocast on
            supported CUDA devices, else fp32; ``"off"``: always fp32; the
            YAML-boolean spellings of these names also resolve, see
            `validate_amp`). The memory probes size patches in the same mode.
            Outputs are fp32 in either mode. Defaults to "auto".
        channels_last_3d (bool, optional): opt in to running 3D models on CUDA
            in the channels_last_3d memory format (kept off on CPU and for 2D
            models). The memory probes size patches in the same layout.
            Outputs are unaffected. Defaults to False.

    Returns:
        np.ndarray: The predicted boundaries as a 3D (Z, Y, X) or 4D (C, Z, Y, X) array, normalized between 0 and 1.

    Raises:
        ValueError: If neither `model_name`, `model_id`, nor `config_path` are provided.
        ValueError: If the patch or halo shape cannot run on the model.
    """
    amp = validate_amp(amp)
    if config_path is not None:  # Safari mode for custom models outside zoos
        logger.info("Safari prediction: Running model from custom config path.")
        model, model_config, model_path = model_zoo.get_model_by_config_path(
            config_path, model_weights_path
        )
    elif model_id is not None:  # BioImage.IO zoo mode
        logger.info("BioImage.IO prediction: Running model from BioImage.IO model zoo.")
        model, model_config, model_path = model_zoo.get_model_by_id(model_id)
    elif model_name is not None:  # PanSeg zoo mode
        logger.info("Zoo prediction: Running model from PanSeg official zoo.")
        model, model_config, model_path = model_zoo.get_model_by_name(
            model_name, model_update=model_update
        )
    else:
        raise ValueError(
            "Either `model_name` or `model_id` or `model_path` must be provided."
        )
    state = torch.load(model_path, map_location="cpu", weights_only=True)

    if "model_state_dict" in state:  # Model weights format may vary between versions
        state = state["model_state_dict"]
    model.load_state_dict(state)

    # One architecture traversal per prediction: the default halo, the
    # pre-probe checks and the final validation all share this geometry.
    geometry = model_geometry(model)
    user_halo = patch_halo is not None
    if patch_halo is None:
        patch_halo = geometry.halo
        logger.info(f"Computed theoretical minimum halo from model: {patch_halo}")

    if input_layout == "YX":
        raw_shape = (1,) + raw.shape
    elif input_layout == "ZYX":
        raw_shape = raw.shape
    elif input_layout == "CYX":
        raw_shape = (1,) + raw.shape[1:]
    elif input_layout == "CZYX":
        raw_shape = raw.shape[1:]

    assert len(raw_shape) == 3
    # A manual patch is used verbatim, even on a small image; only the derived
    # patch (from an auto-sized domain) must fit the architectural minimum.
    if patch is None:
        geometry.check_input(raw_shape)

    # Predict on an aligned domain: SliceBuilder flushes the last patch start
    # to `i - k`, which stays on the phase grid only when the domain is a
    # multiple of the increment. Reflect-pad the domain up to it; the result is
    # cropped back to `raw_shape` below.
    domain_shape = geometry.aligned_shape(raw_shape)
    auto_patch = patch is None
    if auto_patch:
        if user_halo:
            logger.info(
                f"Using the manually specified halo {patch_halo} while deriving a "
                "phase-aligned patch."
            )
        patch, patch_halo = find_feasible_patch_and_halo_shapes(
            model,
            model_config["in_channels"],
            domain_shape,
            patch_halo,
            device,
            amp=amp,
            channels_last_3d=channels_last_3d,
            geometry=geometry,
        )

    geometry.check_patch(patch, patch_halo)
    if auto_patch:
        _warn_inefficient_auto_patch(geometry, patch, patch_halo)

    oversized_dims = [
        f"{dim}: patch {p} > domain {s}"
        for dim, p, s in zip(("Z", "Y", "X"), patch, domain_shape)
        if p > s
    ]
    if oversized_dims:
        raise ValueError(
            f"Patch shape {tuple(patch)} is bigger than the aligned domain shape "
            f"{tuple(domain_shape)} in: {', '.join(oversized_dims)}. "
            "Reduce the patch size, or leave it unset to derive a feasible one."
        )

    logger.info(
        f"For raw in shape {raw.shape}: set patch shape {patch}, set halo shape {patch_halo}"
    )

    predictor = ArrayPredictor(
        model=model,
        in_channels=model_config["in_channels"],
        out_channels=model_config["out_channels"],
        device=device,
        patch=patch,
        patch_halo=patch_halo,
        single_batch_mode=single_batch_mode,
        headless=False,
        verbose_logging=False,
        disable_tqdm=disable_tqdm,
        tracker=tracker,
        amp=amp,
        channels_last_3d=channels_last_3d,
    )

    if int(model_config["in_channels"]) > 1:  # if multi-channel input
        raw = fix_layout_to_CZYX(raw, input_layout)
        multichannel_input = True
    else:
        raw = fix_layout_to_ZYX(raw, input_layout)
        multichannel_input = False
    raw = raw.astype("float32")
    augs = get_test_augmentations(
        raw
    )  # normalization stats of the original raw, before the domain pad
    raw = pad_to_shape(raw, domain_shape)
    stride = geometry.stride_shape(patch)
    slice_builder = SliceBuilder(
        raw, label_dataset=None, patch_shape=patch, stride_shape=stride
    )
    test_dataset = ArrayDataset(
        raw,
        slice_builder,
        augs,
        halo_shape=patch_halo,
        multichannel=multichannel_input,
        verbose_logging=False,
    )

    prediction = predictor(test_dataset)
    # `raw` was reflect-padded up to the phase-aligned domain, so the map covers
    # the padded extent; the public API returns the raw extent. The last three
    # axes are spatial even for 2D models (singleton z), so C stays untouched.
    z, y, x = raw_shape
    return prediction[..., :z, :y, :x]