Metadata-Version: 2.4
Name: salcon
Version: 0.1.2
Summary: S-ALCoN: Soft-Gated Adaptive Layer Condensation Networks - Learning Dynamic Compression Ratios for Hierarchical Feature Selection
Author-email: Ananda Jana <ajana2006@gmail.com>
License: MIT
Project-URL: Homepage, https://github.com/anandajana/salcon
Project-URL: Documentation, https://github.com/anandajana/salcon#readme
Project-URL: Repository, https://github.com/anandajana/salcon
Project-URL: Bug Tracker, https://github.com/anandajana/salcon/issues
Keywords: salcon,s-alcon,alcnet,deep-learning,neural-networks,compression,feature-selection,adaptive-architecture,pytorch,machine-learning
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: torch>=1.9.0
Requires-Dist: numpy>=1.19.0
Requires-Dist: tqdm>=4.50.0
Requires-Dist: matplotlib>=3.3.0
Requires-Dist: scikit-learn>=0.24.0
Provides-Extra: dev
Requires-Dist: pytest>=6.0; extra == "dev"
Requires-Dist: pytest-cov>=2.12; extra == "dev"
Requires-Dist: black>=22.0; extra == "dev"
Requires-Dist: flake8>=3.9; extra == "dev"
Requires-Dist: mypy>=0.910; extra == "dev"
Provides-Extra: viz
Requires-Dist: matplotlib>=3.3.0; extra == "viz"
Provides-Extra: examples
Requires-Dist: torchvision>=0.10.0; extra == "examples"
Dynamic: license-file
Dynamic: requires-python

# S-ALCoN: Soft-Gated Adaptive Layer Condensation Networks

[![Python 3.8+](https://img.shields.io/badge/python-3.8%2B-blue.svg)](https://www.python.org/downloads/)
[![PyTorch 2.0+](https://img.shields.io/badge/PyTorch-2.0%2B-ee4c2c.svg)](https://pytorch.org/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

> Learning Dynamic Compression Ratios for Hierarchical Feature Selection

S-ALCoN (Soft-Gated Adaptive Layer Condensation Networks) is a PyTorch neural network architecture that learns layer-wise feature retention ratios during training.

Instead of fixing the degree of feature retention before training, S-ALCoN introduces a learnable retention parameter for each hidden layer and uses a differentiable median-centered gating mechanism to softly suppress less informative activations.

The model is designed to provide:

- Learnable layer-wise retention ratios
- Differentiable feature selection
- Task-adaptive compression behavior
- End-to-end optimization with standard backpropagation
- No separate Neural Architecture Search (NAS) stage
- Interpretable layer-wise compression statistics

---

## 1. Introduction & Basic Structure

### The Problem With Fixed Architectures

Conventional neural networks typically use a fixed architecture such as:

```text
784 → 256 → 128 → 64 → 10
```

The layer widths are selected before training and remain fixed throughout optimization. This forces the practitioner to decide, in advance, how much representational capacity each layer should have — which creates several challenges:

* **Manual architecture design:** The appropriate amount of feature capacity may vary between tasks.
* **Redundant representations:** Some tasks may not require the full representational capacity of every hidden layer.
* **Expensive architecture search:** Searching over multiple architectures can require repeated training.
* **Limited interpretability:** Conventional architectures do not directly expose how much feature capacity is being retained at each layer.

### The S-ALCoN Idea

S-ALCoN keeps the underlying layer *dimensions* fixed, but learns how strongly each hidden layer should *retain* its features. Every filterable hidden layer gets its own trainable "retention ratio" `ρ`, which the network learns jointly with the task itself — no separate search stage required.

```text
Input
  |
  v
Hidden Layer 1
  |
  |  Learnable retention ratio ρ¹
  v
Hidden Layer 2
  |
  |  Learnable retention ratio ρ²
  v
Hidden Layer 3
  |
  |  Learnable retention ratio ρ³
  v
Output
```

The learned ratios describe the amount of feature information the gating mechanism attempts to retain at each layer.

**Important:** S-ALCoN performs **soft, differentiable feature selection** rather than physically deleting neurons or changing the tensor dimensions of the network during training. The weight matrices stay the same shape throughout — what changes is how strongly each feature is allowed to pass through.

### Basic Layer Structure

Every gated hidden layer follows the same pipeline:

```text
Linear Transformation
        |
        v
Batch Normalization (optional)
        |
        v
ReLU
        |
        v
Median-Centered Soft Gate
        |
        v
Soft Feature Selection
        |
        v
Dropout (optional)
        |
        v
Next Layer
```

The final output layer is **not** gated — it's a plain linear layer producing task outputs (logits for classification, values for regression).

The full mathematical details of each stage are covered in [Section 4](#4-full-mathematical-explanation).

---

## 2. Installation

### Install from PyPI

```bash
pip install salcon
```

### Install from Source

Clone the repository:

```bash
git clone https://github.com/anandaASURE/sALCoN.git
cd salcon
```

Install the package in editable mode:

```bash
pip install -e .
```

### Requirements

The package is built around:

* Python 3.8+
* PyTorch 2.0+
* NumPy
* scikit-learn
* matplotlib
* tqdm

`matplotlib` is used by the analysis and visualization utilities. `scikit-learn` is used by the `prepare_data` utility in the implementation.

---

## 3. Usage Guide

### 3.1 Quick Start — Classification

```python
import torch
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset

from salcon import sALCoN, sALCoNTrainer, set_seed


# Reproducibility
set_seed(42)


# Example classification dataset
X = torch.randn(1000, 784)
y = torch.randint(0, 10, (1000,))

dataset = TensorDataset(X, y)

train_loader = DataLoader(
    dataset,
    batch_size=32,
    shuffle=True
)


# Create S-ALCoN
model = sALCoN(
    layer_sizes=[784, 256, 128, 64, 10],
    initial_ratios=[0.7, 0.7, 0.7],
    initial_alpha=10.0,
    dropout_rate=0.3,
    use_batchnorm=True
)


# Optimizer
optimizer = optim.Adam(
    model.parameters(),
    lr=1e-3
)


# Trainer
trainer = sALCoNTrainer(
    model=model,
    optimizer=optimizer,
    lambda_sparse=0.001,
    lambda_ratio=0.01,
    task="classification"
)


# Train
history = trainer.fit(
    train_loader,
    epochs=10,
    verbose=True
)


# Inspect learned compression ratios
ratios = model.get_compression_ratios()

print("Learned compression ratios:")
print(ratios)
```

A typical result has the form:

```text
{
    'layer_1': 0.XX,
    'layer_2': 0.XX,
    'layer_3': 0.XX
}
```

The exact values depend on the dataset, architecture, optimizer, initialization, and training configuration.

### 3.2 Classification With Validation Data

A validation loader can optionally be supplied:

```python
history = trainer.fit(
    train_loader,
    val_loader,
    epochs=50,
    verbose=True
)
```

The trainer records:

* Training loss
* Training accuracy
* Validation loss
* Validation accuracy
* Layer-wise compression ratios

### 3.3 Regression

S-ALCoN also supports continuous-target regression.

```python
import torch
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset

from salcon import sALCoN, sALCoNTrainer


# Example regression dataset
X = torch.randn(500, 10)
y = torch.randn(500, 1)

dataset = TensorDataset(X, y)

train_loader = DataLoader(
    dataset,
    batch_size=32,
    shuffle=True
)


# Create model
model = sALCoN(
    layer_sizes=[10, 16, 8, 1]
)


# Optimizer
optimizer = optim.Adam(
    model.parameters(),
    lr=1e-3
)


# Regression trainer
trainer = sALCoNTrainer(
    model=model,
    optimizer=optimizer,
    task="regression"
)


# Train
history = trainer.fit(
    train_loader,
    epochs=10
)
```

For regression, the trainer uses mean squared error by default and tracks `R²` as the reported metric.

### 3.4 Custom Compression Ratios

Initial retention ratios can be supplied manually.

For:

```text
784 → 256 → 128 → 64 → 10
```

there are three filterable hidden layers, so three initial ratios can be specified:

```python
model = sALCoN(
    layer_sizes=[784, 256, 128, 64, 10],
    initial_ratios=[0.5, 0.4, 0.3]
)
```

These values are initializations only — the ratios remain trainable and can change during optimization.

### 3.5 Custom Gate Sharpness

The initial value of the gate sharpness parameter can be changed:

```python
model = sALCoN(
    layer_sizes=[784, 256, 128, 64, 10],
    initial_alpha=10.0
)
```

`alpha` is itself implemented as a trainable parameter within each gated layer.

### 3.6 Batch Normalization and Dropout

Batch normalization is enabled by default:

```python
model = sALCoN(
    layer_sizes=[784, 256, 128, 64, 10],
    use_batchnorm=True   # or False to disable
)
```

Dropout is enabled by default with a rate of `0.3`:

```python
model = sALCoN(
    layer_sizes=[784, 256, 128, 64, 10],
    dropout_rate=0.3      # set to 0 or None to disable
)
```

### 3.7 Compression Analysis

S-ALCoN includes a `CompressionAnalyzer` for examining the behavior of the learned gates.

```python
from salcon import CompressionAnalyzer

analyzer = CompressionAnalyzer(
    model,
    device="cpu"
)

# Average feature selection probabilities per layer
survival = analyzer.compute_feature_survival(
    dataloader,
    max_batches=10
)

# How learned compression ratios evolved during training
fig = analyzer.plot_compression_evolution(history)

# Training / validation curves
fig = analyzer.plot_training_curves(history)

# Compare learned ratios across different tasks/runs
fig = analyzer.plot_layer_comparison(compression_ratios_dict)

# Summary statistics
stats = analyzer.get_summary_stats(history)
```

`get_summary_stats` returns final training accuracy, final validation accuracy, best validation accuracy, final compression ratios, and the average compression ratio.

### 3.8 Saving and Loading Models

```python
# Save (model state, optimizer state, training history)
trainer.save_model("salcon_checkpoint.pt")

# Load
trainer.load_model("salcon_checkpoint.pt")
```

### 3.9 Reproducibility

```python
from salcon import set_seed

set_seed(42)
```

This sets seeds for Python's `random` module, NumPy, and PyTorch. CUDA seeds are also configured when CUDA is available.

> **Note:** `count_parameters`, `get_device`, and `prepare_data` exist inside `utils.py` but are **not** currently re-exported at the package level (only `set_seed` is). To use them, import directly from the module, e.g. `from salcon.utils import count_parameters`.

### 3.10 Package Exports

```python
from salcon import (
    sALCoN,
    SALCoN,          # alias of sALCoN
    sALCoNLayer,
    sALCoNTrainer,
    CompressionAnalyzer,
    set_seed
)
```

`SALCoN` is provided purely as a naming-convention alias of `sALCoN` — both refer to the same class.

---

## 4. Full Mathematical Explanation

This section covers the complete math behind each stage of a gated S-ALCoN layer, plus the training objective.

### 4.1 Linear Transformation

For an input `x`:

```text
z = Wx + b
```

The implementation applies an optional batch-normalization layer immediately after the linear transformation.

### 4.2 ReLU Activation

The (optionally normalized) representation is passed through ReLU:

```text
h = ReLU(z)
```

### 4.3 Median-Centered Soft Gating

For every hidden feature, S-ALCoN computes its activation relative to the median activation of that layer:

```text
s_j = sigmoid(α (h_j − median(h)))
```

where:

* `h_j` is the activation of feature `j`
* `median(h)` is the median activation across the feature dimension
* `α` controls the sharpness of the gate (default `α = 10.0`)
* `s_j` is the resulting feature selection score, in `(0, 1)`

Features above the layer's median activation get pushed toward a selection score near `1`; features below it get pushed toward `0`. The sharpness `α` controls how "hard" this soft cutoff is — higher `α` approaches a hard threshold at the median, lower `α` gives a gentler, more graded selection.

### 4.4 Soft Feature Selection

The activation is multiplied by its own selection score:

```text
a_j = h_j × s_j
```

Features with lower relative activation receive smaller selection scores (and are proportionally suppressed), while features with higher relative activation receive larger scores (and pass through mostly unchanged). This operation is fully differentiable and is optimized jointly with the rest of the network via ordinary backpropagation — there's no discrete/hard masking step that would block gradients.

### 4.5 Dropout

Dropout can optionally be applied after the gated activations, with a default rate of `0.3`. It can be disabled with `dropout_rate=0` or `dropout_rate=None`.

### 4.6 The Learnable Retention Ratio `ρ`

Each gated hidden layer carries its own trainable retention parameter, stored internally in **logit space**:

```text
θρ
```

and converted into a valid ratio via sigmoid:

```text
ρ = sigmoid(θρ)
```

Storing the parameter in logit space and squashing it with a sigmoid guarantees `ρ ∈ (0, 1)` at all times while still allowing unconstrained gradient-based optimization of `θρ`.

The default initialization is `ρ = 0.7` for every filterable hidden layer, independent of that layer's width. For example:

```python
model = sALCoN([784, 256, 128, 64, 10])
```

creates three filterable hidden layers, each initialized with `ρ = 0.7`. The output layer is never gated and has no associated `ρ`.

### 4.7 Full Training Objective

S-ALCoN combines the task loss with two regularization terms:

```text
L_total = L_task + λ_sparse · L_sparse + λ_ratio · L_ratio
```

**Task loss** — cross-entropy for classification, MSE for regression (or a custom `criterion` you supply):

```text
L_task = CrossEntropy(output, target)      # classification
L_task = MSE(output, target)               # regression
```

**Sparsity loss** — the average selection score across all filterable layers, encouraging the network toward sparser (more compressed) representations:

```text
L_sparse = (1 / N) · Σ mean(s^(i))
```

where `N` is the number of filterable hidden layers. This value is returned by the model as `sparsity_loss`.

**Ratio matching loss** — encourages the *actual* average selection score of each layer to converge to its own *learned target* ratio `ρ`, tying the abstract retention parameter to the gate's real behavior:

```text
L_ratio = (1 / N) · Σ (mean(s^(i)) − ρ^(i))²
```

**Default regularization weights** (changeable at trainer initialization):

```text
λ_sparse = 0.001
λ_ratio  = 0.01
```

### 4.8 Model API Reference

#### `sALCoN`

```python
sALCoN(
    layer_sizes,
    initial_ratios=None,
    initial_alpha=10.0,
    dropout_rate=0.3,
    use_batchnorm=True
)
```

| Parameter        | Type              |  Default | Description                                                                                      |
| ---------------- | ----------------- | -------: | ------------------------------------------------------------------------------------------------ |
| `layer_sizes`    | `list`            | Required | Network dimensions in the form `[input, hidden..., output]`.                                     |
| `initial_ratios` | `list`            |   `None` | Initial retention ratios for filterable hidden layers. Defaults to `0.7` for every hidden layer. |
| `initial_alpha`  | `float`           |   `10.0` | Initial sharpness parameter for the sigmoid gate.                                                |
| `dropout_rate`   | `float` or `None` |    `0.3` | Dropout probability applied after soft feature selection.                                        |
| `use_batchnorm`  | `bool`            |   `True` | Enables batch normalization before ReLU in gated layers.                                         |

**Methods:**

* `forward(x)` → returns `output, sparsity_loss, ratio_loss`
* `predict(x)` → returns model output for the current implementation
* `get_compression_ratios()` → returns the current learned `ρ` per filterable layer, e.g. `{'layer_1': 0.68, 'layer_2': 0.54, 'layer_3': 0.41}`

#### `sALCoNLayer`

```python
sALCoNLayer(
    input_size,
    output_size,
    initial_ratio=0.7,
    initial_alpha=10.0,
    dropout_rate=0.3,
    use_batchnorm=True
)
```

A single gated hidden layer performing: `Linear → BatchNorm (optional) → ReLU → Median-centered sigmoid gate → Soft feature selection → Dropout (optional)`.

Exposes `layer.get_compression_ratio()` to retrieve its current learned `ρ`.

#### `sALCoNTrainer`

```python
sALCoNTrainer(
    model,
    optimizer,
    lambda_sparse=0.001,
    lambda_ratio=0.01,
    device="cpu",
    task="classification",
    criterion=None
)
```

| Parameter       | Type                    |            Default | Description                                  |
| --------------- | ----------------------- | -----------------: | --------------------------------------------- |
| `model`         | `nn.Module`             |           Required | S-ALCoN model.                               |
| `optimizer`     | `torch.optim.Optimizer` |           Required | Optimizer used for training.                 |
| `lambda_sparse` | `float`                 |            `0.001` | Weight of the sparsity loss.                 |
| `lambda_ratio`  | `float`                 |             `0.01` | Weight of the ratio matching loss.           |
| `device`        | `str`                   |            `"cpu"` | Training device.                             |
| `task`          | `str`                   | `"classification"` | Either `"classification"` or `"regression"`. |
| `criterion`     | callable                |             `None` | Optional custom loss function.               |

`trainer.fit(train_loader, val_loader=None, epochs=50, verbose=True)` returns a `history` dict with `train_loss`, `train_acc`, `val_loss`, `val_acc`, and `compression_ratios` (for regression, the `*_acc` fields hold `R²` instead).

---

## Benchmark Results

| Dataset                | Type                   | Architecture              | Best Validation Accuracy | Average Retention Ratio |
| ---------------------- | ---------------------- | ------------------------- | -----------------------: | ----------------------: |
| **MNIST**              | Image Classification   | `[784, 256, 128, 64, 10]` |               **98.24%** |                    0.42 |
| **FashionMNIST**       | Image Classification   | `[784, 256, 128, 64, 10]` |               **88.51%** |                    0.51 |
| **California Housing** | Binarized Tabular      | `[8, 6, 4, 2]`            |               **85.49%** |                    0.38 |
| **Wine**               | Tabular Classification | `[13, 10, 8, 3]`          |               **97.22%** |                    0.31 |
| **Iris**               | Tabular Classification | `[4, 6, 4, 3]`            |               **96.67%** |                    0.28 |

### California Housing Note

For the reported benchmark, the continuous California Housing target is converted into a binary classification problem using the median target as the threshold, giving the architecture `8 → 6 → 4 → 2` with two output logits and cross-entropy loss.

For actual continuous California Housing **regression**, use:

```python
trainer = sALCoNTrainer(model, optimizer, task="regression")
```

---

## Research Motivation

S-ALCoN explores whether the amount of feature capacity required at different levels of a neural network can be learned jointly with the task itself, rather than treating architecture design and model training as completely separate processes. The resulting compression ratios can be inspected after training, providing a direct view of the feature-retention behavior learned by the network.

---

## Citation

If you use S-ALCoN in research or academic work, please cite:

```bibtex
@article{jana2026salcon,
  title={S-ALCoN: Soft-Gated Adaptive Layer Condensation Networks for Dynamic Hierarchical Feature Selection},
  author={Jana, Ananda},
  journal={preprint},
  year={2026}
}
```

---

## License

This project is licensed under the MIT License. See the `LICENSE` file for details.

---

## Author

**Ananda Jana**
Indian Institute of Science Education and Research Thiruvananthapuram (IISER TVM)
Kerala, India

---

## Project Status

S-ALCoN is an actively developed research implementation. The current release focuses on:

* Learnable layer-wise retention ratios
* Median-centered differentiable gating
* Classification and regression training
* Compression-ratio tracking
* Feature-survival analysis
* Training visualization
* Model checkpointing
