This post describes the model architecture and data pipeline behind Saranga, an Android app for real-time Carnatic raga identification that runs entirely on-device.
1. Introduction
Carnatic raga identification is a deceptively hard problem. A raga is not merely defined by Aarohana or Avarohana - it is a complex probabilistic system governing which notes to use, how long to hold them, how to transition between them, and which melodic phrases are characteristic. Two ragas can share an identical set of notes and still be unmistakable to an experienced listener. The differentiating signal lives in the fine-grained temporal structure of the performance, not in a bag of frequencies.
Automatic raga identification has been studied in the MIR literature for quite some time now using a variety of ML, signal processing, and statistical approaches. My goal was to build an interactive mobile-first tool that runs in real time, generates immediate predictions as a live performance unfolds, and continuously updates its confidence as it hears more audio. Saranga is the result of that effort. It currently supports 244 ragas and runs entirely offline on-device.
2. End-to-End Pipeline
The full pipeline from raw audio to raga prediction looks like this:
[Microphone / Audio Input]
|
v
+-----------------------+
| Source Separation | (Full Mode only)
| (vocal stem extract) | strips accompaniment, isolates vocals
+-----------------------+
|
v
+-----------------------+
| Pitch Extraction & |
| Tokenisation | voiced/unvoiced tokens per frame
+-----------------------+
| (token sequence)
v
+-----------------------+
| Window Accumulation | one window = a model context's worth
| | of pitch tokens
+-----------------------+
|
v
+-----------------------+
| Hierarchical Raga | <-- described in Section 4
| Transformer Model |
+-----------------------+
|
v
[Predicted Raga + Confidence]
Full Mode engages the source separator before pitch extraction, giving the model a cleaner vocal signal.
Alapana Mode skips the separator and feeds the mixed audio directly to the pitch extractor which is faster and more memory-efficient, at a small accuracy cost.
3. Feature Extraction: From Audio to Pitch Tokens
3.1 Why Pitch?
Standard audio processing relies on time-frequency representations such as spectrograms which encode timbre alongside pitch. For raga identification, timbre is largely irrelevant - the characteristic phrases of a raga are melodic. A Shankarabharanam sounds like a Shankarabharanam regardless of whether it is sung by a male or female vocalist, performed by a violin or a flute, or recorded in a concert hall or a living room. Using raw pitch discards irrelevant information and keeps the input cheap to compute.
3.2 Pitch Extraction and Tokenisation
Pitch is extracted using the pYIN algorithm. pYIN produces a fundamental frequency estimate and a voiced/unvoiced decision per frame. Frames where no clear pitch is detected — silence, consonants, percussion-only passages — receive a special unvoiced token.
The continuous pitch estimate is then discretised into a compact vocabulary of MIDI-cent values, covering the practical vocal range of Carnatic singers across both male and female registers. This discretisation is preferable to continuous pitch for two reasons: it naturally encodes the semi-tonal pitch classes that define Carnatic svaras, and it makes the input compatible with a standard learned embedding layer.
These tokens are the sole input to the model.
3.3 Shruti Normalisation
Different vocalists perform at different base pitches (shruti). Rather than applying explicit tonic normalisation, which adds latency and fails on untuned or dynamic recordings, the model is trained with pitch-shift augmentation of ±3 semitones. The natural gender split in the training data places male tonics around C/D and female tonics around G/A. Applying ±3-semitone augmentation smooths pitch variation across singers, giving the model implicit shruti invariance.
4. Model Architecture: Hierarchical Raga Transformer
The core challenge is that raga-defining phrases can span several seconds. A single window of tokens (a model’s context size) may not contain enough material for confident identification, but accumulating several consecutive windows usually does. This motivates the hierarchical design. All in, it comes to around 22 million parameters which is feather light by modern standards and can be run at full precision on most hardware.
4.1 Architecture Overview
Input: Pitch & Timestamp Sequence
│
▼
┌────────────────────────────────────────────────────────┐
│ LOCAL WINDOW ENCODER │
│ │
│ • Dilated 1D CNN ➔ Captures local pitch movements │
│ • Local Transformer ➔ Produces single Window Vector │
└────────────────────────────────────────────────────────┘
│
▼ (Sequence of Window Vectors)
┌────────────────────────────────────────────────────────┐
│ GLOBAL CAUSAL ENCODER │
│ │
│ • Causal Transformer ➔ Integrates performance over │
│ time without looking ahead │
└────────────────────────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────────────────┐
│ CLASSIFICATION HEAD │
│ │
│ • MLP + Softmax ➔ Real-time Raga Probabilities │
└────────────────────────────────────────────────────────┘
4.2 Local Encoder
Each window is encoded independently by the Local Encoder.
Input representation. We feed both the raw pitch tokens as well as log-relative timestamps which give the encoder a sense of when a note occurs within the frame.
CNN feature extractor. The embedded sequence is fed to a stack of 1D residual blocks with dilated convolutions. Dilated convolutions expand the receptive field to span several seconds of local context (capturing gamaka oscillations and note approach patterns), while the 1D residual blocks stabilize deep feature extraction and retain fine-grained pitch representations across temporal scales.
Local Transformer. A Transformer encoder attends across the compressed sequence. A learned CLS token is prepended; its output is taken as the fixed-size window embedding.
4.3 Global Encoder
The sequence of window embeddings is passed to a causal Transformer. The causal mask ensures window k can only attend to windows 1…k - a necessary condition for streaming inference. The output at the last window position summarises everything heard so far and is passed to the task head.
4.4 Task Head and Training
The model uses a standard MLP + softmax head trained with cross-entropy loss. The key differences in our setup are:
- Robustness training: Each training sample is presented with a randomly drawn number of windows (with the remainder padded and masked). This forces the model to produce useful predictions from partial context, matching real-world conditions at the start of a session when little audio has accumulated.
- Log-dampened class loss: Used to compensate for the long-tailed raga distribution where common ragas have orders of magnitude more training examples than rare ones. In turn, this weighting makes the model slightly prone to predicting a similar but rarer raga in lieu of its more popular cousin (e.g., predicting Manji over Bhairavi).
5. Inference Engine
The trained model is exported to ONNX and served by a custom C++ inference engine that is bundled directly into the Flutter app via Dart FFI, running the full pipeline in a background thread with no network calls.
5.1 Streaming Inference Diagram
┌────────────────────────────────────────────────────────┐
│ FLUTTER APP (Dart UI) │
│ Streams live audio chunks ➔ Displays real-time ragas │
└────────────────────────────────────────────────────────┘
│
▼ (Dart FFI)
┌────────────────────────────────────────────────────────┐
│ C++ RAGA ENGINE │
│ │
│ 1. Source Separator ➔ Isolates vocal stem │
│ (Bypassed in Alapana Mode) │
│ │
│ 2. Pitch Extractor ➔ Frame-level pitch detection │
│ │
│ 3. ONNX Runtime ➔ Runs Hierarchical Model over │
│ pitch buffer + rolling context │
└────────────────────────────────────────────────────────┘
│
▼ (Predictions & Confidence)
┌────────────────────────────────────────────────────────┐
│ UI DISPLAY │
└────────────────────────────────────────────────────────┘
6. Dataset
The model is trained on around 4000 hours of Carnatic vocal recordings across 244 ragas assembled from archival and publicly available sources.
7. Results and Lessons Learned
Rare ragas are often easier to identify than common ones. The model is more adept at identifying rare ragas than the more common ones. Rare ragas frequently have an unmistakable signature or even a single canonical composition. The model can effectively memorise this signature. Common ragas like Bhairavi or Kalyani are harder because they have more sibling ragas with substantially overlapping phrase inventories, and also a larger body of performances with significant differences in phrasing.
The global context is necessary but not always sufficient early on. Anecdotally, the global context helps a lot in stabilising performance but the eventual consistency of the model (i.e. correct convergence after an incorrect first or second prediction) is not sufficiently tested.
Alapana mode works reasonably well with light percussion. Alapana mode is reasonably good even for performances with some percussion, especially when the piece being performed is short. In such cases, Full Mode may not even accumulate enough data by the time the piece ends. On short Tukdas, running Alapana mode might be better since some prediction is better than none. Also, short pieces tend to be popular kritis or bhajans which are generally well represented in the training data, so the model can hazard a decent guess.
Full Mode works better in noisier environments. Source separation inadvertently acts as a denoising step, making Full Mode a much better candidate for environments with a lot of ambient noise. The trade-off is that it takes considerably longer to run and requires at least 6GB of RAM, making it impractical to run on low to medium-end phones and even certain high-end RAM-deficient devices (Apple products).
Forced prediction is a design trade-off. The model cannot withhold a prediction once a full window has accumulated. If the beginning of a performance is noisy/low-signal (ambient noise, singer adjusting voice, amplifier issues, etc.), it can push the model into a wrong answer early in the session. The practical recommendation is to start a new session once clean audio is available.
8. Future Work
- Continuous Fine-tuning: Fine-tune on more data to make the model more accurate.
- Expanded raga support: Expand to include an even wider range of ragas.
- Hardware acceleration: Inference is currently purely CPU-based, which allows most devices to run the app. But several devices now come with special hardware and APIs to run heavy FLOPs (NNAPI on Android and CoreML on iOS). Once the APIs stabilize and hardware becomes widely available, Saranga will switch to hardware acceleration to conserve battery and improve inference latency.
- Automatic raga change detection: Ideally, raga changes should be automatically detected. This would allow a listener to keep a single session active for an entire concert.
- Characteristic phrase recognition: Rather than predicting a raga directly, the model would learn to identify the characteristic phrases that define the raga. This is a considerably harder and more open-ended problem than flat classification — the label space is now more diffuse and ground truth annotation is much more expensive. But it unlocks true out-of-distribution predictions (the model could describe any unfamiliar raga by its phrases rather than failing silently), and it opens a path toward building a genuine reasoning model of Carnatic music rather than a statistical pattern matcher.
A public repository with model architecture code is planned once cleanup is complete.
9. Try It Now!
Want to give Saranga a spin on your Android device?
Saranga is now available on Google Play! You can install the app directly from the Play Store:
👉 Download Saranga on Google Play
Feedback, bug reports, and suggestions are always welcome — feel free to share your thoughts in the saranga-testers Google Group or reach out directly!