Skip to content

Commit 75341a0

Browse files
committed
docs: revise quickstart and faq answers
1 parent 4427bff commit 75341a0

2 files changed

Lines changed: 132 additions & 114 deletions

File tree

docs/getting_started/faq.md

Lines changed: 99 additions & 109 deletions
Original file line numberDiff line numberDiff line change
@@ -6,37 +6,54 @@ Frequently asked questions about DeepTab and troubleshooting common issues.
66

77
### What's the difference between DeepTab v1 and v2?
88

9-
Version 2.0 introduces a fully typed data layer (`TabularDataset`, `TabularDataModule`, `FeatureSchema`, `TabularBatch`) that makes it easier to work with tabular data at a lower level. The high-level estimator API remains unchanged and is still the recommended interface for most users.
9+
v2.0 is a ground-up restructuring of DeepTab. The high-level estimator workflow stays familiar, but the package layout, configuration objects, and import paths have changed. Three things affect existing code:
1010

11-
Key changes in v2.0:
11+
1. **Import paths** were reorganised under the `deeptab` namespace.
12+
2. **Config classes** dropped their `Default` prefix (`DefaultMambularConfig` is now `MambularConfig`) and settings are split across `MambularConfig` (architecture), `PreprocessingConfig` (feature handling), and `TrainerConfig` (training).
13+
3. **Data modules** were renamed to `TabularDataModule` and `TabularDataset`; the old `Mambular*` aliases are deprecated.
1214

13-
- **Automatic stratification** for classification tasks
14-
- **Typed batch containers** with device management
15-
- **Feature schema tracking** with metadata
16-
- **Consistent label shapes** across tasks
17-
- Deprecated `MambularDataset`/`MambularDataModule` aliases (use `TabularDataset`/`TabularDataModule`)
15+
The split-config API is the main thing you reach for day to day. In v1 every option was a flat keyword argument on the estimator; in v2 the same options live in dedicated config objects, while `fit`, `predict`, and `evaluate` behave exactly as before.
16+
17+
```python
18+
# v1: settings passed as flat keyword arguments
19+
model = MambularClassifier(d_model=128, n_layers=4, numerical_preprocessing="ple")
20+
```
21+
22+
```python
23+
# v2: settings grouped into focused config objects
24+
from deeptab.configs import MambularConfig, PreprocessingConfig
25+
26+
model = MambularClassifier(
27+
model_config=MambularConfig(d_model=128, n_layers=4),
28+
preprocessing_config=PreprocessingConfig(numerical_preprocessing="ple"),
29+
)
30+
```
31+
32+
You only pass the configs you want to change; `MambularClassifier()` uses sensible defaults for all three.
1833

1934
```{important}
20-
**Note on v1 support**: DeepTab v1 is no longer supported following the v2.0 release. The changes in package structure and API design were substantial enough that maintaining backward compatibility would have compromised the improvements in v2. If you're using v1 in production, we recommend planning a migration to v2. Pin your dependency to `deeptab<2.0` if you need to continue using v1, but be aware that no bug fixes or security updates will be provided for the v1 branch.
35+
v2.0 is not backward compatible with v1, and v1 is no longer maintained. If you need to stay on v1, pin `deeptab<2.0`, but note that the v1 branch receives no bug fixes or security updates.
2136
```
2237

23-
See the [Overview](overview) for details on the new data API.
38+
See the [Overview](overview) for the full v2 data API, and the [homepage](../homepage) for the complete list of new features.
2439

2540
### Which model should I use?
2641

2742
```{tip}
2843
When in doubt, start with `MambularClassifier` or `MambularRegressor`.
2944
```
3045

31-
Mambular tends to work well across a variety of tabular problems. For a full selection guide by dataset size, feature type, and compute constraints, see the [Model Comparison](../model_zoo/comparison_tables) page.
46+
Mambular tends to work well across a variety of tabular problems.
3247

33-
Quick pointers:
48+
| Goal | Try |
49+
| ------------------------------- | -------------------- |
50+
| Strong general-purpose baseline | `TabM` or `Mambular` |
51+
| Many categorical features | `TabTransformer` |
52+
| Fastest baseline | `MLP` or `ResNet` |
53+
| Uncertainty estimates | any `LSS` variant |
54+
| Interpretability | `NODE` or `NDTF` |
3455

35-
- **Strong general-purpose baseline**`TabM` or `Mambular`
36-
- **Many categorical features**`TabTransformer`
37-
- **Fastest baseline**`MLP` or `ResNet`
38-
- **Uncertainty estimates** → any `LSS` variant
39-
- **Interpretability**`NODE` or `NDTF`
56+
These are starting points, not rules. For the detailed comparison by dataset size, feature mix, and compute budget, see the [Model Comparison](../model_zoo/comparison_tables) page.
4057

4158
### Do I need a GPU?
4259

@@ -51,14 +68,15 @@ For a full per-model breakdown including the cost driver for each architecture,
5168

5269
### How do I know if my GPU is being used?
5370

54-
Check CUDA availability:
71+
Print the hardware DeepTab can see:
5572

5673
```python
57-
import torch
58-
print(f"CUDA available: {torch.cuda.is_available()}")
74+
from deeptab import print_hardware_info
75+
76+
print_hardware_info()
5977
```
6078

61-
DeepTab will automatically use the first available GPU. If CUDA is available but you're not seeing speedups, ensure you're training on a reasonably large dataset, since small batches may not benefit from GPU parallelism.
79+
The report lists the CPU, any CUDA GPUs, the Apple Silicon MPS backend, and the `accelerator` DeepTab would pick by default. DeepTab uses the first available GPU automatically. If a GPU is listed but you're not seeing speedups, make sure you're training on a reasonably large dataset, since small batches may not benefit from GPU parallelism.
6280

6381
### Can I use DeepTab with PyTorch dataloaders?
6482

@@ -112,7 +130,7 @@ model = MambularClassifier()
112130
model.fit(df, y, max_epochs=50)
113131
```
114132

115-
The pretab preprocessor (used internally) applies median imputation for numerical features and mode imputation for categoricals by default.
133+
The internal [PreTab](https://github.com/OpenTabular/PreTab) preprocessor imputes missing values as part of fitting, so you do not need a separate imputation step. The exact strategy follows the configured `PreprocessingConfig`; with the defaults it uses PreTab's built-in imputation for numerical and categorical features.
116134

117135
### Can I use NumPy arrays instead of DataFrames?
118136

@@ -182,49 +200,67 @@ model.fit(df, y, max_epochs=50)
182200

183201
### How do I speed up training?
184202

185-
```{tip}
186-
Combine GPU acceleration with larger batch sizes and early stopping for fastest training.
203+
Start by checking what hardware DeepTab is actually using, then adjust the parts that matter most.
204+
205+
**1. Confirm you are on an accelerator.** Print the detected hardware:
206+
207+
```python
208+
from deeptab import print_hardware_info
209+
210+
print_hardware_info()
187211
```
188212

189-
Several options:
213+
If the recommended accelerator is `cpu` but you expect a GPU, install a CUDA-enabled PyTorch build (see the [installation guide](installation)). DeepTab uses the first available GPU automatically, but you can also force it explicitly:
190214

191-
1. **Use a GPU**: install CUDA-enabled PyTorch
192-
2. **Increase batch size**: larger batches are more efficient when memory allows (`TrainerConfig(batch_size=...)`)
193-
3. **Reduce epochs**: rely on early stopping instead of a fixed epoch count
194-
4. **Use multi-worker data loading**: pass `num_workers` through `dataloader_kwargs` in `fit()`
215+
```python
216+
model.fit(X_train, y_train, accelerator="gpu", max_epochs=100)
217+
```
218+
219+
**2. Use a batch size that keeps the accelerator busy.** GPUs and MPS only pay off with larger batches. Try 256 or more; on very small datasets (under ~1K rows) the CPU can be faster because of transfer overhead.
220+
221+
**3. Check the learning rate.** Training that crawls for many epochs is often a learning-rate problem, not a hardware one. The default is conservative; a slightly higher rate can converge in far fewer epochs. Raise it carefully and watch the loss.
222+
223+
**4. Lean on early stopping instead of a fixed epoch count**, and speed up data loading with extra workers.
195224

196225
```python
197226
from deeptab.configs import TrainerConfig
198227

199228
model = MambularClassifier(
200229
trainer_config=TrainerConfig(
201-
batch_size=512, # Larger batch size
202-
patience=10, # Early stopping
230+
batch_size=512, # keep the accelerator busy
231+
lr=1e-3, # raise from the default if convergence is slow
232+
patience=10, # stop once the validation metric plateaus
203233
)
204234
)
205235

206236
# num_workers is a DataLoader option, so pass it via dataloader_kwargs
207237
model.fit(X_train, y_train, dataloader_kwargs={"num_workers": 4}, max_epochs=100)
208238
```
209239

210-
### Training is slow on GPU
211-
212240
```{note}
213-
GPUs need larger batch sizes to show a speedup over CPU. Small batches or datasets may run faster on CPU.
241+
A GPU is not always faster. For small datasets or tiny batches the transfer overhead can outweigh the speedup, and the CPU may win. Benchmark both on your data.
242+
```
243+
244+
```{warning}
245+
Raising the learning rate too far makes training unstable and the loss can diverge. If that happens, lower it again and see [Training is unstable (loss explodes)](#training-is-unstable-loss-explodes).
214246
```
215247

216-
Ensure you're using GPU:
248+
### How do I use multiple GPUs?
249+
250+
Pass Lightning's multi-device arguments straight through `fit()`. Set `devices` to the number of GPUs (or a list of indices) and choose a `strategy` such as `"ddp"`:
217251

218252
```python
219-
import torch
220-
print(torch.cuda.is_available()) # Should be True
253+
model = MambularClassifier()
254+
model.fit(
255+
X_train, y_train,
256+
accelerator="gpu",
257+
devices=2, # or [0, 1] to pick specific GPUs
258+
strategy="ddp", # distributed data parallel
259+
max_epochs=100,
260+
)
221261
```
222262

223-
If True but still slow:
224-
225-
- **Small batches**: GPU efficiency requires larger batches (try 256+)
226-
- **Small dataset**: for < 1K samples, CPU may be faster due to transfer overhead
227-
- **CPU bottleneck**: increase `num_workers` via `dataloader_kwargs` in `fit()` for faster data loading
263+
For finer control over the distributed setup, drive `TabularDataModule` with your own Lightning module (advanced usage).
228264

229265
### How do I use early stopping?
230266

@@ -384,7 +420,7 @@ batch = batch.to("cuda") # Move entire batch
384420

385421
The estimator API handles this automatically.
386422

387-
## Model-specific
423+
## Choosing a model
388424

389425
### What's the difference between Mambular and MambaTab?
390426

@@ -522,84 +558,38 @@ between releases.
522558

523559
### Can I use custom loss functions?
524560

525-
Not directly through the estimator API. If you need custom losses, use `TabularDataModule` with a custom Lightning module.
526-
527-
### How do I extract learned features?
528-
529-
Access intermediate representations:
561+
Yes, for classifiers. Pass `loss_fct` to `fit()`: either an `nn.Module` instance, which is used as-is, or a registered loss name such as `"focal"`, `"bce"`, or `"cross_entropy"`, which is built and combined with any `class_weight` you set.
530562

531563
```python
532-
model = MambularClassifier()
533-
model.fit(X_train, y_train, max_epochs=50)
534-
535-
# The raw architecture lives on the fitted Lightning module (internal API)
536-
architecture = model._task_model.estimator
537-
```
538-
539-
This is an advanced use case. See the source code for details.
540-
541-
### Can I use multiple GPUs?
542-
543-
DeepTab uses the first available GPU by default. For multi-GPU training, use Lightning's distributed strategies directly with `TabularDataModule` (advanced usage).
544-
545-
## Contributing and support
546-
547-
### How do I report a bug?
548-
549-
Open an issue on [GitHub](https://github.com/OpenTabular/DeepTab/issues) with:
550-
551-
- DeepTab version (`import deeptab; print(deeptab.__version__)`)
552-
- Python version
553-
- PyTorch version
554-
- Minimal reproducible example
555-
- Full error traceback
556-
557-
### How do I request a feature?
558-
559-
Open a feature request on [GitHub](https://github.com/OpenTabular/DeepTab/issues) describing:
560-
561-
- The use case
562-
- Why existing features don't solve it
563-
- Proposed API (if applicable)
564-
565-
### How do I contribute?
566-
567-
See the [Contributing guide](../developer_guide/contributing) for:
568-
569-
- Setting up the development environment
570-
- Running tests
571-
- Code style guidelines
572-
- Submitting pull requests
573-
574-
### Where can I get help?
575-
576-
- Check this FAQ first
577-
- Search [GitHub issues](https://github.com/OpenTabular/DeepTab/issues)
578-
- Open a new issue for bugs or questions
579-
- Join discussions on the GitHub repo
564+
import torch.nn as nn
565+
from deeptab.models import MambularClassifier
580566

581-
## Performance comparisons
567+
model = MambularClassifier()
582568

583-
### How does DeepTab compare to XGBoost?
569+
# A custom nn.Module loss
570+
model.fit(X_train, y_train, loss_fct=nn.CrossEntropyLoss(label_smoothing=0.1))
584571

585-
It depends on the dataset:
572+
# Or a registered loss by name (here combined with class weighting)
573+
model.fit(X_train, y_train, loss_fct="focal", class_weight="balanced")
574+
```
586575

587-
- **Small datasets (< 1K samples)**: XGBoost often wins
588-
- **Large datasets (> 10K samples)**: DeepTab competitive or better, especially with complex feature interactions
589-
- **Categorical-heavy data**: XGBoost may be more efficient
590-
- **Need for uncertainty**: DeepTab LSS models provide distributional predictions
576+
```{note}
577+
When `loss_fct` is an `nn.Module`, it is used as given and `class_weight` is ignored. Regressors use the task default loss; to swap the loss for a regression model, drive `TabularDataModule` with a custom Lightning module.
578+
```
591579

592-
Use both and compare on your specific data. DeepTab makes experimentation easy.
580+
### How do I extract learned features?
593581

594-
### Is DeepTab faster than training PyTorch manually?
582+
Use the public `encode()` method on a fitted model. It runs the backbone and returns dense representations as a tensor of shape `(n_samples, embedding_dim)`, which you can feed into clustering, similarity search, or another downstream model.
595583

596-
No, DeepTab uses PyTorch under the hood. It provides convenience, not speed improvements. However, it does:
584+
```python
585+
model = MambularClassifier()
586+
model.fit(X_train, y_train, max_epochs=50)
597587

598-
- Apply sensible defaults (early stopping, LR scheduling)
599-
- Handle device management automatically
600-
- Provide efficient data loading
588+
embeddings = model.encode(X_test) # torch.Tensor, shape (n_samples, embedding_dim)
589+
print(embeddings.shape)
590+
```
601591

602-
So while not "faster", it helps you get to a working model more quickly.
592+
If you also passed external `embeddings` at fit time, supply them again with `model.encode(X_test, embeddings=...)` so the rows stay aligned.
603593

604594
## Still have questions?
605595

docs/getting_started/quickstart.md

Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,6 @@ model.fit(X_train, y_train, max_epochs=50)
3939

4040
# Evaluate on test set
4141
metrics = model.evaluate(X_test, y_test)
42-
# Returns e.g. {"accuracy": 0.91, "auroc": 0.96, "log_loss": 0.28}
4342
print(f"Test accuracy: {metrics['accuracy']:.3f}")
4443

4544
# Make predictions
@@ -87,7 +86,6 @@ X_train, X_test, y_train, y_test = train_test_split(
8786
model = FTTransformerRegressor()
8887
model.fit(X_train, y_train, max_epochs=50)
8988

90-
# Evaluate (returns RMSE, MAE, R² for regression)
9189
metrics = model.evaluate(X_test, y_test)
9290
print(f"Test RMSE: {metrics['rmse']:.3f}")
9391

@@ -250,9 +248,39 @@ Use the `.deeptab` extension for saved models. DeepTab accepts any extension but
250248

251249
Note: `save()` writes a fitted estimator artifact, not just neural-network weights. The artifact includes the architecture/config, trained weights, fitted preprocessing state, feature schema and column order, task metadata such as classifier `classes_`, and package versions for debugging reloads across environments.
252250

253-
## Going further
251+
## Inference guide
254252

255-
These examples cover the core workflow. For hyperparameter optimisation, custom optimizers and schedulers, cross-validation, working with embeddings, comparing architectures, and debugging, see the [Tutorials](../tutorials/imbalance_classification), [Core Concepts](../core_concepts/training_and_evaluation), and the [FAQ](faq).
253+
For serving a fitted model, DeepTab provides `InferenceModel`, a read-only wrapper built for production. It loads an artifact, validates incoming data against the training schema, and predicts, while deliberately hiding `fit` and other training methods so deployment code cannot retrain a model by accident.
254+
255+
```python
256+
from deeptab import InferenceModel
257+
258+
# Load a saved artifact (one type, regardless of the architecture inside)
259+
model = InferenceModel.from_path("my_model.deeptab")
260+
261+
# Validate new data against the training schema, then predict
262+
X_valid = model.validate_input(X_new)
263+
predictions = model.predict(X_valid)
264+
265+
# Task-specific outputs
266+
probabilities = model.predict_proba(X_valid) # classifiers only
267+
params = model.predict_params(X_valid) # LSS models only
268+
```
269+
270+
`validate_input` checks that the expected columns are present, reorders them to the training order, and reports missing or unexpected columns with clear messages. You can also wrap an already-fitted estimator without going through disk using `InferenceModel.from_estimator(estimator)`.
271+
272+
```{note}
273+
`InferenceModel` exposes only the prediction method that matches the task: `predict_proba` for classifiers and `predict_params` for `LSS` models. Calling the wrong one raises a clear error, so serving code never branches on the concrete model class.
274+
```
275+
276+
If you only need a quick prediction during experimentation, calling `predict` on the fitted estimator directly works too:
277+
278+
```python
279+
predictions = model.predict(X_new) # estimator or InferenceModel
280+
metrics = trained_estimator.evaluate(X_new, y_new)
281+
```
282+
283+
See [Inference and deployment](../core_concepts/inference) for the full production contract, schema-validation options, and introspection helpers.
256284

257285
## Next steps
258286

@@ -263,4 +291,4 @@ Now that you've run your first models, explore:
263291
- **[API Reference](../api/models/index)**: Full documentation of all models and configs
264292
- **[FAQ](faq)**: Answers to common questions
265293

266-
For questions or issues, check the [FAQ](faq) or open an issue on [GitHub](https://github.com/OpenTabular/DeepTab/issues).
294+
For questions or issues, open an issue on [GitHub](https://github.com/OpenTabular/DeepTab/issues).

0 commit comments

Comments
 (0)