stan-dev / stan-dev/stanc3

[BUG] Compiler optimizations can prevent bounds checks

Open
#1,295 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug cpp-codegen optimization robustness
Dominant language
OCaml
Stars
160
Forks
59
Avg merge
21h 45m
Merged PRs (30d)
26

Description

Current Behavior:

Enabling compiler optimizations currently stops emitting a default assignment for a variable if it is immediately assigned to (https://github.com/stan-dev/stanc3/pull/1029). However, this changes the behavior of those very assign functions when it comes to bounds checks:

https://github.com/stan-dev/stan/blob/4ec109a21e5bd1cd43eed724ef286aadec3b5e7a/src/stan/model/indexing/access_helpers.hpp#L58

This means the same model:

parameters {
  vector[3] y;
}

model {
  vector[2] x;
  x = y;
  y ~ std_normal();
  // prevent copy-elision and dead-code-elimination on x
  x[1] = 0;
  print(x);
}

Will throw an error at --O0:

Unrecoverable error evaluating the log probability at the initial value.
Exception: vector assign rows: assigning variable x (2) and right hand side rows (3) must match in size (in '../../ml/stanc3/bounds.stan', line 12, column 4 to column 10)
Exception: vector assign rows: assigning variable x (2) and right hand side rows (3) must match in size (in '../../ml/stanc3/bounds.stan', line 12, column 4 to column 10)

But will sample to completion at --O1.

Expected Behavior:

Bounds checks are applied uniformly.

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the model from the issue with --O0 and --O1, then inspect the bounds-checking behavior around src/stan/model/indexing/access_helpers.hpp. Compare the generated or executed paths for the assignment and confirm that both optimization levels report the same size-mismatch error.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp, ocaml
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.