# Fabric and Side Effects

Configuration reference for `default_fabric` and the built-in side effect system.

## default_fabric

Source: `common/__init__.py:79-242`

Factory function that creates a `lightning.fabric.Fabric` instance with pre-configured loggers and callbacks.

### Full signature

```python
def default_fabric(
    root_dir: str = './',
    dir_name: str = 'lightning_logs',
    version: str | None = None,
    save_every_k: int | None = None,
    save_best: bool = True,
    keep_best_k: int | None = 3,
    monitor: str = 'loss',
    monitor_on: Literal['train', 'val'] = 'val',
    less_is_better: bool = True,
    enabled: EnabledConfig | bool | None = None,
    fn_custom_logger: ((str) -> list[Logger]) | None = None,
    fn_custom_callback: ((str) -> list[FabricCallbackProtocol]) | None = None,
    **fabric_kwargs,
) -> Fabric
```

### Parameters

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `root_dir` | `str` | `'./'` | Root directory for logs |
| `dir_name` | `str` | `'lightning_logs'` | Subdirectory name |
| `version` | `str \| None` | `None` | Version string. Default: `v{datetime}`. Supports `{time_str}` placeholder. |
| `save_every_k` | `int \| None` | `None` | Save checkpoint every K epochs (periodic, non-best) |
| `save_best` | `bool` | `True` | Whether to save best model checkpoints |
| `keep_best_k` | `int \| None` | `3` | Keep top-K best checkpoints (True Top-K strategy) |
| `monitor` | `str` | `'loss'` | Metric name to monitor for best model. Supports `train_` and `val_` prefixes. |
| `monitor_on` | `Literal['train', 'val']` | `'val'` | Which phase's metrics to monitor |
| `less_is_better` | `bool` | `True` | Whether lower metric values are better |
| `enabled` | `dict \| bool \| None` | `None` | Side effect toggle config (see below) |
| `fn_custom_logger` | callable | `None` | `(version: str) -> list[Logger]` |
| `fn_custom_callback` | callable | `None` | `(version: str) -> list[FabricCallbackProtocol]` |
| `**fabric_kwargs` | | | Passed directly to `Fabric(...)` (e.g. `accelerator`, `precision`, `devices`) |

### Return value

Returns a `Fabric` instance. **Note**: `fabric.launch()` is NOT called automatically. Use `ctx.launch()` after creating `FabricTrainingContext`.

### Directory layout

```
{root_dir}/
  {dir_name}/
    {version}/
      checkpoints/
        best_epoch=5.ckpt
        best_epoch=10.ckpt
      hparams.yaml
      train-info.txt
      events.out.tfevents.*    (TensorBoard)
      events.out.tfevents.json (auto-converted)
```

Default version format: `v2026_03_18-16_30_00`

## EnabledSideEffect config

Controls which built-in loggers and callbacks are active.

### Default values

```python
DEFAULT_ENABLED = {
    'csv_logger': False,
    'tensorboard_logger': True,
    'print_info_cb': True,
    'save_train_info': True,
    'save_checkpoints_cb': True,
    'save_hparams_cb': True,
}
```

### Usage patterns

```python
# Use all defaults
fabric = default_fabric()

# Disable everything
fabric = default_fabric(enabled=False)

# Enable everything
fabric = default_fabric(enabled=True)

# Selective: disable all, then enable specific
fabric = default_fabric(enabled={'*': False, 'print_info_cb': True})

# Selective: keep defaults, override specific
fabric = default_fabric(enabled={'csv_logger': True, 'save_checkpoints_cb': False})
```

### Wildcard behavior

When `'*'` key is present in the dict:
1. All keys are first set to the `'*'` value
2. Then specific keys override the wildcard

```python
enabled={'*': False, 'print_info_cb': True}
# Result: everything OFF except print_info_cb
```

### What each key controls

| Key | What it creates | Notes |
|-----|----------------|-------|
| `csv_logger` | `CSVLogger` + `ParseCSVLogfile` callback | Writes `metrics.csv`, auto-converts to Excel/YAML |
| `tensorboard_logger` | `TensorBoardLogger` | Writes TensorBoard event files |
| `print_info_cb` | `PrintTrainInfo` callback | Prints epoch metrics to console |
| `save_train_info` | Controls `PrintTrainInfo.out_dir` | When True, also saves to `train-info.txt` |
| `save_checkpoints_cb` | `SaveCheckpoints` callback | Saves model checkpoints |
| `save_hparams_cb` | `SaveHparams` callback | Saves `hparams.yaml` |

### Auto-injected callbacks

When any logger is enabled, two additional callbacks are automatically added:
- `FabricLogMetrics`: logs all metrics to all loggers (train/val batch and epoch level)
- `SaveLoggersFinally`: flushes loggers on train_end/test_end, converts TensorBoard to JSON

## fn_custom_logger / fn_custom_callback

Both receive the `version` string and must return a list.

```python
def my_loggers(version: str) -> list[Logger]:
    from lightning.fabric.loggers import WandbLogger
    return [WandbLogger(project='my-project', name=version)]

def my_callbacks(version: str) -> list[FabricCallbackProtocol]:
    from zyplib.train.common.callbacks import EarlyStopping, LRSchedulerCallback
    return [
        EarlyStopping(monitor='loss', patience=20),
        LRSchedulerCallback(my_scheduler, interval='epoch'),
    ]

fabric = default_fabric(
    fn_custom_logger=my_loggers,
    fn_custom_callback=my_callbacks,
)
```

## Fabric kwargs

Common `**fabric_kwargs` passed to `Fabric(...)`:

| Kwarg | Example | Description |
|-------|---------|-------------|
| `accelerator` | `'gpu'`, `'cpu'`, `'auto'` | Hardware accelerator |
| `devices` | `1`, `[0, 1]`, `'auto'` | Device count or IDs |
| `precision` | `'32-true'`, `'16-mixed'`, `'bf16-mixed'` | Training precision |
| `strategy` | `'ddp'`, `'fsdp'` | Distributed strategy |

```python
fabric = default_fabric(
    accelerator='gpu',
    devices=1,
    precision='16-mixed',
)
```
