Amortized Planning with Large-Scale Transformers: A Case Study on Chess https://openreview.net/forum?id=XlpipUGygX
OpenReview
Amortized Planning with Large-Scale Transformers: A Case Study on...
This paper uses chess, a landmark planning problem in AI, to assess transformers’ performance on a planning task where memorization is futile — even at a large scale. To this end, we release...
MathArena: Evaluating LLMs on Uncontaminated Math Competitions https://matharena.ai/
Chiral Instabilities in Driven-Dissipative Quantum Liquids https://arxiv.org/abs/2502.04443
arXiv.org
Chiral Instabilities in Driven-Dissipative Quantum Liquids
We investigate the nonequilibrium dynamics of periodically driven Tomonaga-Luttinger liquids (TLLs) coupled to a thermal bath using a Floquet-Lindblad approach. When the coupling to the bath...
It's All in The [MASK]: Simple Instruction-Tuning Enables BERT-like Masked Language Models As Generative Classifiers https://arxiv.org/abs/2502.03793
arXiv.org
It's All in The [MASK]: Simple Instruction-Tuning Enables...
While encoder-only models such as BERT and ModernBERT are ubiquitous in real-world NLP applications, their conventional reliance on task-specific classification heads can limit their applicability...
MATH-Perturb: Benchmarking LLMs' Math Reasoning Abilities against Hard Perturbations https://arxiv.org/abs/2502.06453
arXiv.org
MATH-Perturb: Benchmarking LLMs' Math Reasoning Abilities...
Large language models have demonstrated impressive performance on challenging mathematical reasoning tasks, which has triggered the discussion of whether the performance is achieved by true...
Competitive Programming with Large Reasoning Models https://arxiv.org/abs/2502.06807
arXiv.org
Competitive Programming with Large Reasoning Models
We show that reinforcement learning applied to large language models (LLMs) significantly boosts performance on complex coding and reasoning tasks. Additionally, we compare two general-purpose...
From Pixels to Components: Eigenvector Masking for Visual Representation Learning https://arxiv.org/abs/2502.06314
arXiv.org
From Pixels to Components: Eigenvector Masking for Visual...
Predicting masked from visible parts of an image is a powerful self-supervised approach for visual representation learning. However, the common practice of masking random patches of pixels...
Gemstones: A Model Suite for Multi-Faceted Scaling Laws https://arxiv.org/abs/2502.06857
arXiv.org
Gemstones: A Model Suite for Multi-Faceted Scaling Laws
Scaling laws are typically fit using a family of models with a narrow range of frozen hyper-parameter choices. In this work we study scaling laws using a wide range of architecture and...
Training Language Models for Social Deduction with Multi-Agent Reinforcement Learning https://arxiv.org/abs/2502.06060
arXiv.org
Training Language Models for Social Deduction with Multi-Agent...
Communicating in natural language is a powerful tool in multi-agent settings, as it enables independent agents to share information in partially observable settings and allows zero-shot...
Diverse Inference and Verification for Advanced Reasoning https://arxiv.org/abs/2502.09955
arXiv.org
Diverse Inference and Verification for Advanced Reasoning
Reasoning LLMs such as OpenAI o1, o3 and DeepSeek R1 have made significant progress in mathematics and coding, yet find challenging advanced tasks such as International Mathematical Olympiad (IMO)...
Forwarded from Находки в опенсорсе
Что такое GIL в Python?
Кажется, один из золотых вопросов для всех питонистов на собеседованиях.
Обычно, на встречный вопрос "а что конкретно в питоне является GIL?" не может ответить ни один спрашивающий.
Сегодня мы закроем данный пробел в знаниях питонистов.
Global Interpreter Lock не позволяет работать более чем одному треду работать с Python API за раз. Его можно отключить через
Обратите внимание на ключевую фразу "c Python API". С системными треды могут и должны работать в режиме настоящей параллельности, без GIL. Что и позволяет получить ускорение при использовании
Знакомьтесь – вот структура GIL
Как можно отпустить GIL?
На уровне C есть макросы: Py_BEGIN_ALLOW_THREADS и Py_END_ALLOW_THREADS, которые отпускают GIL в нужных местах. Пример из модуля mmap:
Или time.sleep, который тоже дает работать другим тредам, пока ждет.
Что происходит, когда мы используем данный макрос? Они разворачиваются в:
Когда вызывается PyEval_SaveThread и GIL отпускается, то на самом деле мы просто помечаем текущий PyThreadState как:
И вызываем _PyEval_ReleaseLock, который уже правильно изменит
Как итог – текущий стейт теряет возможность вызывать какие-либо Python АПИ. Даже, например
Как треды берут GIL?
Смотрим на thread_run из
Там используется PyEval_AcquireThread, который берет GIL в конкретном треде для работы с Python API.
И дальше – отпускаем.
В следующих сериях поговорим про переключение тредов, ParkingLot API, Mutex'ы и прочее.
Обсуждение: сталкивались ли вы на собесах с вопросами про GIL? Стало ли теперь понятнее?
| Поддержать | YouTube | GitHub | Чат |
Кажется, один из золотых вопросов для всех питонистов на собеседованиях.
Обычно, на встречный вопрос "а что конкретно в питоне является GIL?" не может ответить ни один спрашивающий.
Сегодня мы закроем данный пробел в знаниях питонистов.
Global Interpreter Lock не позволяет работать более чем одному треду работать с Python API за раз. Его можно отключить через
--disable-gil
в 3.13+, но сегодня мы про такое не будем.Обратите внимание на ключевую фразу "c Python API". С системными треды могут и должны работать в режиме настоящей параллельности, без GIL. Что и позволяет получить ускорение при использовании
threading
, когда C код поддерживает такой способ.Знакомьтесь – вот структура GIL
_gil_runtime_state
и поведение в ceval_gil.c
.Как можно отпустить GIL?
На уровне C есть макросы: Py_BEGIN_ALLOW_THREADS и Py_END_ALLOW_THREADS, которые отпускают GIL в нужных местах. Пример из модуля mmap:
Py_BEGIN_ALLOW_THREADS
m_obj->data = mmap(NULL, map_size, prot, flags, fd, offset);
Py_END_ALLOW_THREADS
Или time.sleep, который тоже дает работать другим тредам, пока ждет.
Что происходит, когда мы используем данный макрос? Они разворачиваются в:
{
PyThreadState *_save;
_save = PyEval_SaveThread();
// your code here
PyEval_RestoreThread(_save);
}
PyThreadState
является текущим состоянием треда в CPython. Внутри хранится много контекста. Нас особо сильно интересует часть с полями про GIL:
struct PyThreadState {
struct {
unsigned int initialized:1;
/* Has been bound to an OS thread. */
unsigned int bound:1;
/* Has been unbound from its OS thread. */
unsigned int unbound:1;
/* Has been bound aa current for the GILState API. */
unsigned int bound_gilstate:1;
/* Currently in use (maybe holds the GIL). */
unsigned int active:1;
/* Currently holds the GIL. */
unsigned int holds_gil:1;
} _status;
// Thread state (_Py_THREAD_ATTACHED, _Py_THREAD_DETACHED, _Py_THREAD_SUSPENDED).
int state;
// ...
}
Когда вызывается PyEval_SaveThread и GIL отпускается, то на самом деле мы просто помечаем текущий PyThreadState как:
tstate->_status.active = 0;
tstate->_status.unbound = 1;
tstate->_status.holds_gil = 0;
tstate->state = detached_state;
И вызываем _PyEval_ReleaseLock, который уже правильно изменит
_gil_runtime_state
. Как итог – текущий стейт теряет возможность вызывать какие-либо Python АПИ. Даже, например
Py_DECREF
, и в тредах есть свой refcount, который работает локально, чтобы можно было его вызывать без GIL.Как треды берут GIL?
Смотрим на thread_run из
_threadmodule.c
.
_PyThreadState_Bind(tstate);
PyEval_AcquireThread(tstate);
_Py_atomic_add_ssize(&tstate->interp->threads.count, 1);
Там используется PyEval_AcquireThread, который берет GIL в конкретном треде для работы с Python API.
И дальше – отпускаем.
В следующих сериях поговорим про переключение тредов, ParkingLot API, Mutex'ы и прочее.
Обсуждение: сталкивались ли вы на собесах с вопросами про GIL? Стало ли теперь понятнее?
| Поддержать | YouTube | GitHub | Чат |
GitHub
cpython/Include/internal/pycore_gil.h at fb2d325725dcc881868b576b9d0d9f4bf7f24fe0 · python/cpython
The Python programming language. Contribute to python/cpython development by creating an account on GitHub.
Functional recovery of adult brain tissue arrested in time during cryopreservation by vitrification https://www.biorxiv.org/content/10.1101/2025.01.22.634384
bioRxiv
Functional recovery of adult brain tissue arrested in time during cryopreservation by vitrification
Cryopreserving adult brain tissue is challenging due to damage from ice formation, and traditional freezing methods fail to maintain neural architecture and function. Vitrification is a promising alternative to freezing, but its application to brain tissue…
Theory of correlated insulators and superconductor at ν = 1 in twisted WSe2 https://www.nature.com/articles/s41467-025-56816-8
Nature
Theory of correlated insulators and superconductor at ν = 1 in twisted WSe2
Nature Communications - Recently, superconductivity intertwined with an insulating phase at a commensurate band-filling was discovered in twisted bilayer WSe2. Here, the authors theoretically...
Extracting the topological spins from bulk multipartite entanglement https://arxiv.org/abs/2502.12259
arXiv.org
Extracting the topological spins from bulk multipartite entanglement
We address the problem of identifying a 2+1d topologically ordered phase using measurements on the ground-state wavefunction. For non-chiral topological order, we describe a series of bulk...
Roadmap to fault tolerant quantum computation using topological qubit arrays https://arxiv.org/abs/2502.12252
arXiv.org
Roadmap to fault tolerant quantum computation using topological...
We describe a concrete device roadmap towards a fault-tolerant quantum computing architecture based on noise-resilient, topologically protected Majorana-based qubits. Our roadmap encompasses four...
Scaling Test-Time Compute Without Verification or RL is Suboptimal https://arxiv.org/abs/2502.12118
arXiv.org
Scaling Test-Time Compute Without Verification or RL is Suboptimal
Despite substantial advances in scaling test-time compute, an ongoing debate in the community is how it should be scaled up to enable continued and efficient improvements with scaling. There are...
Interferometric single-shot parity measurement in InAs–Al hybrid devices https://www.nature.com/articles/s41586-024-08445-2
Nature
Interferometric single-shot parity measurement in InAs–Al hybrid devices
Nature - A device architecture based on indium arsenide–aluminium heterostructures with a gate-defined superconducting nanowire allows single-shot interferometric measurement of fermion...