Skip to content

Synthesis: CRT, signed mul, log-depth sum, sub and mul - #119

Open
HSPyroblast wants to merge 3 commits into
mainfrom
log_depth_generation
Open

Synthesis: CRT, signed mul, log-depth sum, sub and mul#119
HSPyroblast wants to merge 3 commits into
mainfrom
log_depth_generation

Conversation

@HSPyroblast

Copy link
Copy Markdown
Collaborator

This PR extends the capabilities of the generators with the following improvements:

  1. Added support for the AIG basis to most generators.
  2. Implemented logarithmic-depth algorithms for Sum, Mul, and Sub functions.
  3. Added CRT functions for computing the smallest number satisfying given remainders under specified moduli.
  4. Fixed minor logic issues in several functions.

@HSPyroblast
HSPyroblast requested a review from spefk July 26, 2026 10:25
@HSPyroblast
HSPyroblast force-pushed the log_depth_generation branch from 2a62559 to e49ef53 Compare July 28, 2026 17:33
@HSPyroblast
HSPyroblast force-pushed the log_depth_generation branch from e49ef53 to e33d71e Compare July 28, 2026 17:37

@spefk spefk left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Пушу часть комментов, так как подробно ревьюить все методы я буду еще 10 лет. Предлагаю все таки распилить этот ПР на несколько -- в каждом отдельный тип арифметических генераторов -- только так, по кусочкам, сможем эту всю радость отревьюить и вмержить.

if label in mem:
return mem[label]
gate = gates[label]
if gate.gate_type.name == "INPUT":

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Нужно сравнивать не имя, а сам тип "gate.INPUT" (где gate это импортированный модуль), например как тут

if self._gates[_input].gate_type == gate.INPUT

Comment thread cirbo/core/circuit/circuit.py Outdated
gates = self.gates
mem = {}

def depth(label):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

В целом, Ок, но при глубине > ~1000 может падать по RecursionError из-за естественного ограничения на количество рекурсивных вызовов. В идеале стоит переписать на процедурный стиль (через очередь).


:return: integer value representing the maximum depth of the circuit
"""
gates = self.gates

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Минорное имхо: так стоит делать только тогда, когда получение объекта действительно сложное (например self.gates.values.first.gate.gate_type и так далее). А сейчас gates, во первых, перекрывает импорт модуля gates из-за коллизии имени, а во вторых, мешает понимать что gates это не локальная переменная а часть состояния объекта.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

  1. Наименование модуля (файла) должно быть строчными буквами
  2. Не заметил, он не экспортируется никуда? А используется где-то?

Comment thread pyproject.toml
"more-itertools >= 10.8.0",
"typing-extensions >= 4.14.1",
"python-sat >= 1.8.dev26",
"python-sat (==1.8.dev30)",

@spefk spefk Jul 28, 2026

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

А почему не "python-sat 1.9.dev7"? Давай изменения зависимостей (и .lock файл, и апдейт pybind11 и mockturtle соответственно) отдельным ПРом лучше протащим быстренько, чтобы в рамках полученного коммита было видно на что это повлияло (это в целом хорошая практика -- отделять обновления зависимостей/окружения с соответствующими фиксами кода для совместимости от основных изменений в логике)

Я обновил python-sat в отдельном ПРе

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Про все новые методы: нужно проверить coverage новых методов. Тесты должны покрывать все основные ветки выполнение (включая разные положения флагов типа big_endian).

ZERO = xor_two_bits(circuit, x[0], x[0], basis=basis)

_basis = GenerationBasis(basis.upper()) if isinstance(basis, str) else basis
if _basis == GenerationBasis.XAIG:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Здесь, и везде где проверяется значение enum'а, нужно явно прописывать elif с нужным значением enum'a, а в else падать с ошибкой вида "unsupported enum value". Это нужно для того, чтобы при добавлении нового значения enum'a не пришлось бояться за неконсистентность остального кода (самый страшный баг -- который молча портит данные).

Это в целом касается чистоты программирования, не только про enum'ы а про все подобные конструкции.

input_labels: tp.Iterable[gate.Label],
*,
big_endian: bool = False,
basis: tp.Union[str, GenerationBasis] = GenerationBasis.XAIG,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

А зачем разрешать тут str? Может, не надо?

"""
Computes the logical depth of the circuit.

The depth of a circuit is defined as the length of the longest path from any

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Нам разве важно "до любого другого"? Нам тут важно до любого выходного гейта ведь -- до него и нужно замерять?

Comment thread third_party/pybind11

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

В third_party залетели старые версии -- нужно обновить сабмодули и убрать эти изменения из ПРа

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants