Skip to content
Dimitri Robiere PerrietD. R. PerrietCaen, FR — --:--:--EN · FR

Counting strength training reps on the Apple Watch

Counting strength training reps on the Apple Watch — illustration
Fig. 01 — illustration
(00) — In short

CoreMotion, autocorrelation and learning machines from confirmed sets: how Welva’s Apple Watch app counts reps and keeps Health free of duplicate workouts.

Mid-set, nobody wants to touch their phone. So Welva’s Apple Watch app counts reps on the wrist, fills in the set, and lets the iPhone pick up the result. On paper, that’s an accelerometer and a bit of signal processing. In practice, it took a counter that doesn’t lock onto the wrong period, a classifier that knows when to stay quiet, learning that doesn’t reinforce its own mistakes, sync that loses nothing between two devices, and a rule so that each workout appears only once in Health. It’s a personal project, with no client constraints, so I can go into detail.

From sensor to usable signal

All the processing lives in a standalone Swift package, WelvaMotion. It depends neither on the rest of the app nor on a machine learning framework, which means I can build and test it from the command line, without a watch. The real source is a thin wrapper around CMMotionManager: device motion at 100 Hz (user acceleration, rotation rate, gravity), exposed as an AsyncThrowingStream.

The pipeline is fairly standard, but each step is there for a specific reason:

  1. A low-pass FIR filter at 18 Hz (31 taps), then decimation to 50 Hz. Without the filter, noise above 25 Hz would fold back into the band we care about.
  2. Three-second windows with 50% overlap (150 samples, a step of 75).
  3. Segmentation into set, rest and unknown movement, based on energy, regularity and cadence. Hysteresis absorbs a gap of up to 2.25 seconds inside a set, and a set has to last at least 4 seconds. Rest is never sent to the classifier.
  4. PCA by power iteration (12 iterations) finds the main axis of the movement, whatever the watch’s orientation on the wrist. The projected signal goes through a 0.15–1.6 Hz band-pass filter, the physiological range of a rep.

Every threshold sits in a single structure, MotionConfiguration, with a comment justifying each one. That’s what let me adjust one setting without it silently contradicting the segmentation or the counter.

Counting without picking the wrong period

The counter first looks for the period of the movement using autocorrelation. The trap is well known: the global maximum of the autocorrelation often lands on two periods, and taking that peak halves the count. So I take the first significant local maximum, correlated enough (at least 0.35) and prominent enough relative to its neighbours (0.04):

Packages/WelvaMotion/Signal/Autocorrelation.swiftswift
for lag in searchMinimumLag ... searchMaximumLag {
    let score = scores[lag]
    let isMaximum = score >= scores[lag - 1] && score > scores[lag + 1]
    guard isMaximum, score >= configuration.autocorrelationStrengthThreshold else { continue }

    let radius = max(2, Int(Double(lag) * 0.25))
    let prominence = score - max(scores[(lag - radius) ..< lag].min() ?? score,
                                 scores[(lag + 1) ... (lag + radius)].min() ?? score)
    guard prominence >= configuration.autocorrelationProminenceThreshold else { continue }
    return AutocorrelationResult(lag: lag, strength: min(1, max(0, score)), prominence: prominence)
}

The period isn’t what does the counting, though. Peaks are: a local maximum above the median plus 20% of the amplitude, with a refractory window of 55% of the period so the same movement isn’t counted twice. A pause in the middle of a set therefore adds no phantom cycle. Confidence blends the autocorrelation strength (70%) with the regularity of the intervals between peaks (30%). An interval longer than two periods is left out of the regularity calculation: that’s a pause, not an irregular rep.

The most instructive bug came from here. The dominant frequency was measured by DFT over each 3-second window at 50 Hz, giving a resolution of 0.333 Hz. In the 0.15–1.6 Hz band, that left just four possible values. On a set of 616 real sets, every frequency landed on a multiple of 1/3, and seven exercises out of ten came out at 0.333 Hz while their true cadences ranged from 0.353 to 0.515 Hz. The information was already there: the autocorrelation returned a period and I was only reading its strength. The first fix, reading that period window by window, actually made the slowest exercises worse: when the period gets close to the window length, only unusually fast windows produce a peak, so the median is computed on a biased sample. Computing the frequency once over the whole segment brought the error on lunges down from 0.296 to 0.004, and the failure rate from 68% to 5%. I also require at least three periods in the segment before publishing the frequency: with two, you’re back in exactly the zone where the counter knows it picks the wrong period.

Recognising the exercise, or staying quiet

Once the set is counted, a classifier tries to name the movement. Six features (dominant frequency, energy, regularity, robust amplitude, up/down asymmetry, gyroscope share) are compared with prototypes using a normalised Euclidean distance. Beyond a distance of 0.8, or if the margin over the runner-up is too thin, the classifier returns nothing. A close call shouldn’t turn into an arbitrary suggestion.

That caution turned out to be essential. The server catalogue holds 42 patterns, but its contract only carried a cadence: five of the six features arrived as zero, and 31 of the 35 detectable patterns had an exact twin. Zero margin, confidence capped just below the threshold: they couldn’t be classified, whatever the signal. I didn’t loosen a single threshold to get a nicer-looking number. The watch counts the reps and leaves the name blank, which is honest. The way out came from personal learning.

Learning machines from confirmed sets

A personal prototype is built from real measurements, with all six features filled in. It entirely replaces the server centroid for the same pattern. It’s updated as an incremental mean, with no gradient, deterministic and constant in memory. Physical exclusions still come first: a static exercise will never be recognised, whatever has been learned.

Machines, cables and the Smith machine were a separate problem: no generic prototype exists for them, and I didn’t make one up. 101 exercises have a counting profile, including 72 machine, cable or Smith variants, and each variant keeps its own identity. The watch learns their signature only from validated sets. A suggestion on its own trains nothing, and the criteria are strict:

Apps/WelvaWatch/Sources/WatchMachineLearningStore.swiftswift
guard !snapshot.confirmedSetIDs.contains(setID),          // never the same set twice
      let features = measurement.measuredFeatures,
      features.vector.allSatisfy(\.isFinite),
      (0.2 ... 1.2).contains(features.dominantFrequencyHz),
      features.regularity >= 0.5,
      (4 ... 80).contains(repetitions),
      measurement.repetitionConfidence >= 0.65,
      abs(measurement.repetitionCount - repetitions) <= 1, // the counter was nearly right
      (6 ... 180).contains(measurement.segment.durationSeconds)
else { return false }

A set too far from the signature already learned (normalised distance above 0.4) is rejected rather than averaged in. Three confirmed sets are needed before a signature joins recognition. A manual correction only feeds the exercise actually performed: feeding the wrong suggestion would reinforce the mistake. Signatures stay on the watch, separate from the catalogue received from the iPhone, and no raw sample ever leaves the wrist.

The workout routine acts as context. It multiplies the distance by 0.65 for the current exercise and by 0.85 for the other planned exercises. It breaks ties between two close signatures but never creates one: without a real match, the planned name is shown as counting context, not as a recognised movement.

That leaves the most common false positive: walking. It’s as periodic and ample as an exercise. An admission filter, shared by the live count and the final result, requires at least three reps, a confidence of 0.65, 5 seconds of duration and a cadence compatible with the expected exercise (±15%). Before each set, capture waits for one second of stillness (under 0.035 g and 0.25 rad/s), and when CMMotionActivity reports walking, running or a vehicle with medium or high confidence, recognition is suspended and the live count cleared.

Watch, iPhone and Health: a single source of truth

Recognition runs on the wrist. Streaming 50 Hz data over WatchConnectivity would be heavy and pointless: the watch sends compact results (reps, confidence, pattern if any, duration). To show the count during the effort, an analyser rereads a bounded 185-second buffer every 1.5 seconds, without opening a second sensor stream, since CoreMotion only allows one active capture. Only the final decision, published once the user rests, goes to the iPhone.

A platform trap dictates the lifecycle: without an active HealthKit workout session, watchOS suspends the app as soon as the wrist drops. The sensor would stop mid-set with no visible error. So the Health session starts before capture, and stops it when it ends.

On the sync side, the watch persists the finished workout to a durable queue before clearing the active one, and only removes it when it receives an acknowledgement sent after the iPhone’s database transaction. A lost acknowledgement causes a duplicate, which idempotency on the iPhone makes harmless, but never a loss. Along the way I found that the sync tests couldn’t fail: the message envelope was a private enum duplicated in both targets. It now lives in a shared package, with reference bytes for all six messages. Another bug, in Swift 6: WatchConnectivity’s reply closures inherited their class’s @MainActor, and the runtime isolation check crashed the watch on the very first message it sent.

The last point is the one users notice most: a workout done with the watch already exists in Health, with measured calories and heart rate. If the iPhone writes a second one, the Fitness app shows two. So the rule is simple: if the watch took part, the iPhone writes nothing.

Packages/WelvaData/HealthKit/StrengthHealthWritePolicy.swiftswift
guard context.source == .phone else { return .skip(linkedTo: context.watchWorkoutID) }
if let id = context.healthKitID, !id.isEmpty { return .skip(linkedTo: nil) }
if let watchWorkoutID = context.watchWorkoutID { return .skip(linkedTo: watchWorkoutID) }
guard context.isWatchAvailable, context.watchDidMeasure else { return .writeNow }

let deadline = (context.waitingSince ?? context.now).addingTimeInterval(600)
return context.now >= deadline ? .writeNow : .waitForWatch(until: deadline)

The iPhone links the Welva session to the wrist’s HKWorkout. If the ID hasn’t arrived, it waits up to 10 minutes for Health to replicate the watch workout, then writes an estimated fallback workout: an estimate beats nothing. The workout written by the watch carries only the Welva session ID, never the “written by Welva” marker, otherwise deduplication would no longer recognise it as the one holding the measurements. Deleting a Welva session never removes an unmarked Health workout. One late fix was still needed: when HealthKit launched the app, the iPhone’s context arrived after tracking had started, the session identity was never passed to the metrics controller, and every calorie and heartbeat was thrown away. The rest of the app is covered on the Welva project page.

What I’d keep / what I’d change

I’d keep the standalone package and the centralised configuration. Testing the signal processing in a few seconds, without a watch, is what let me find the four-frequency bug and fix it by measuring. I’d also keep the choice of a classifier that stays quiet: a watch that counts correctly without naming the exercise is still useful; a watch that names the wrong exercise loses your trust in the first session.

What I’d change is mostly about measurement. The tests replay synthetic signals (damped sine waves, harmonics, noise, gravity drift, a pause, a knock, walking at 2 Hz) with a fixed seed. They prove the logic and its safeguards, not accuracy on the wrist. I’m missing a bench of real traces, recorded across several people, orientations, loads and machines, before publishing any success rate at all. I’d also revisit the 10-minute window for Health: if the watch is far away or low on battery, the fallback workout gets written and the duplicate comes back. And the server pattern contract should carry all six features. As long as it only carries one, generic recognition stays hobbled, and only personal learning really works.

Related case studyWelva, an iOS nutrition and workout app in SwiftUI →
Counting strength training reps on the Apple Watch — Dimitri Robiere Perriet