Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions stan/math/rev/core/init_chainablestack.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@
#include <thread>
#include <tuple>

#ifdef __APPLE__
#include <pthread.h>
#include <sys/qos.h>
#endif

namespace stan {
namespace math {

Expand All @@ -20,6 +25,10 @@ namespace math {
* hook ensures that each worker thread has an initialized AD tape
* ready for use.
*
* On Apple Silicon, this also sets the thread QoS class to
* USER_INITIATED so that macOS prefers scheduling compute threads
* on performance cores rather than efficiency cores.
*
* Refer to
* https://software.intel.com/content/www/us/en/develop/documentation/tbb-documentation/top/intel-threading-building-blocks-developer-reference/task-scheduler/taskschedulerobserver.html
* for details on the observer concept.
Expand All @@ -37,6 +46,13 @@ class ad_tape_observer final : public tbb::task_scheduler_observer {
~ad_tape_observer() { observe(false); }

void on_scheduler_entry(bool worker) {
#ifdef __APPLE__
#if defined(__arm64__) || defined(__aarch64__)
// Set thread QoS to USER_INITIATED so macOS prefers scheduling
// TBB worker threads on performance cores rather than efficiency cores.
pthread_set_qos_class_self_np(QOS_CLASS_USER_INITIATED, 0);
#endif
Comment on lines +50 to +54
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving this as is should be fine, but pthread_set_qos_class_self_np should work for x86 as well.

#endif
std::lock_guard<std::mutex> thread_tape_map_lock(thread_tape_map_mutex_);
const std::thread::id thread_id = std::this_thread::get_id();
if (thread_tape_map_.find(thread_id) == thread_tape_map_.end()) {
Expand Down