Repository navigation
Expand file tree
/
Copy pathsetup.py
More file actions
executable file
·696 lines (601 loc) · 24.7 KB
/
Copy pathsetup.py
File metadata and controls
executable file
·696 lines (601 loc) · 24.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext as _build_ext
import importlib.util
import subprocess
import os
import sys
import glob
import shutil
from pathlib import Path
# Install dependencies first if needed
def install_fpylll():
"""Install fpylll if not already available."""
try:
import fpylll
print("FPyLLL already installed")
return True
except ImportError:
pass
print("Installing FPyLLL...")
try:
# Try different approaches to install fpylll
pip_commands = [
[sys.executable, '-m', 'pip', 'install', 'fpylll'],
['pip3', 'install', 'fpylll'],
['pip', 'install', 'fpylll']
]
for cmd in pip_commands:
try:
subprocess.check_call(cmd)
print("FPyLLL installed successfully")
return True
except (subprocess.CalledProcessError, FileNotFoundError):
continue
print("Could not install FPyLLL automatically.")
print("Please install it manually using: pip install fpylll")
return False
except Exception as e:
print(f"Error during FPyLLL installation: {e}")
print("You may need to install it manually using: pip install fpylll")
return False
# FPyLLL will be installed during build process via CustomBuildExt
# Now import required modules
try:
from Cython.Build import cythonize
import numpy
except ImportError as e:
print(f"Missing required build dependency: {e}")
sys.exit(1)
class CustomBuildExt(_build_ext):
"""Custom build_ext command to handle dependencies."""
def run(self):
print("Starting CustomBuildExt.run()...")
# Install system dependencies first
try:
self.install_system_deps()
except Exception as e:
print(f"Warning: System dependencies installation failed: {e}")
# Install fpylll if not available
try:
install_fpylll()
except Exception as e:
print(f"Warning: FPyLLL installation failed: {e}")
# Install FPLLL if needed
try:
self.install_fplll()
except Exception as e:
print(f"Warning: FPLLL installation failed: {e}")
print("Dependencies setup complete, starting extension build...")
print(f"Extensions to build: {[ext.name for ext in self.extensions]}")
# Run the build
try:
_build_ext.run(self)
print("Extension build completed successfully")
except Exception as e:
print(f"Extension build failed: {e}")
import traceback
traceback.print_exc()
raise
def install_system_deps(self):
"""Install required system dependencies."""
try:
# Check if parallel-hashmap headers are available
if not os.path.exists('/usr/include/parallel_hashmap/phmap.h'):
print("Installing parallel-hashmap system dependency...")
subprocess.check_call(['sudo', 'apt', 'update'], stdout=subprocess.DEVNULL)
subprocess.check_call(['sudo', 'apt', 'install', '-y', 'libparallel-hashmap-dev'],
stdout=subprocess.DEVNULL)
print("parallel-hashmap installed successfully")
except Exception as e:
print(f"Warning: Could not install system dependencies: {e}")
print("Please install manually: sudo apt install libparallel-hashmap-dev")
def install_fplll(self):
"""Install FPLLL if not available."""
try:
# Check if FPLLL is available
result = subprocess.run(['pkg-config', '--exists', 'fplll'],
capture_output=True)
if result.returncode != 0:
print("Installing FPLLL...")
# Run our install script
subprocess.check_call(['./install-deps.sh'],
cwd=os.path.dirname(os.path.abspath(__file__)))
print("FPLLL installed successfully")
except Exception as e:
print(f"Warning: Could not install FPLLL: {e}")
print("FPLLL may need to be installed manually")
def install_system_dependencies():
"""Install FPLLL and FPyLLL if not available."""
cwd = os.getcwd()
try:
print("Checking for FPLLL system library...")
# Check if fplll is available via pkg-config
fplll_found = False
try:
result = subprocess.run(["pkg-config", "--exists", "fplll"],
capture_output=True, check=False)
if result.returncode == 0:
print("FPLLL found via pkg-config")
fplll_found = True
except FileNotFoundError:
pass
# Check if we're in a virtual environment with fplll installed
if not fplll_found and os.environ.get('VIRTUAL_ENV'):
fplll_lib = Path(os.environ['VIRTUAL_ENV']) / "lib" / "libfplll.so"
if fplll_lib.exists():
print(f"FPLLL found in virtual environment: {fplll_lib}")
fplll_found = True
# Try to find system fplll
if not fplll_found:
for lib_path in ["/usr/lib", "/usr/local/lib", "/usr/lib/x86_64-linux-gnu"]:
if any(Path(lib_path).glob("libfplll*")):
print(f"FPLLL found in system: {lib_path}")
fplll_found = True
break
# Install FPLLL if not found
if not fplll_found:
print("FPLLL not found. Installing from source...")
# Clone and build FPLLL if needed
fplll_dir = Path("g6k-fplll")
if not fplll_dir.exists():
print("Cloning FPLLL...")
subprocess.check_call([
"git", "clone",
"https://github.com/fplll/fplll",
str(fplll_dir)
])
# Build and install FPLLL
os.chdir(fplll_dir)
try:
if not Path("configure").exists():
subprocess.check_call("./autogen.sh", shell=True)
# Configure with appropriate prefix
prefix = os.environ.get('VIRTUAL_ENV', '/usr/local')
subprocess.check_call(f"./configure --prefix={prefix}", shell=True)
# Build and install
subprocess.check_call("make clean", shell=True)
subprocess.check_call("make -j$(nproc)", shell=True)
subprocess.check_call("make install", shell=True)
print("FPLLL installed successfully")
except subprocess.CalledProcessError as e:
print(f"Warning: FPLLL installation failed: {e}")
print("You may need to install FPLLL system dependencies first.")
print("Try: sudo apt-get install libgmp-dev libmpfr-dev")
finally:
os.chdir(cwd)
# Now install FPyLLL
print("Checking for FPyLLL...")
try:
import fpylll
print("FPyLLL already available")
except ImportError:
print("Installing FPyLLL...")
# Clone FPyLLL if needed
fpylll_dir = Path("g6k-fpylll")
if not fpylll_dir.exists():
print("Cloning FPyLLL...")
subprocess.check_call([
"git", "clone",
"https://github.com/fplll/fpylll",
str(fpylll_dir)
])
# Install FPyLLL using pip
try:
os.chdir(fpylll_dir)
subprocess.check_call([sys.executable, "-m", "pip", "install", "."])
print("FPyLLL installed successfully")
except subprocess.CalledProcessError as e:
print(f"Warning: FPyLLL installation failed: {e}")
finally:
os.chdir(cwd)
except Exception as e:
print(f"Error during dependency installation: {e}")
finally:
# Always return to original directory
os.chdir(cwd)
def ensure_parallel_hashmap():
"""Ensure parallel-hashmap dependency is available."""
hashmap_dir = Path("parallel-hashmap")
if not hashmap_dir.exists():
print("Cloning parallel-hashmap dependency...")
subprocess.check_call([
"git", "clone",
"https://github.com/cr-marcstevens/parallel-hashmap",
str(hashmap_dir)
])
def build_kernel_library():
"""Build the kernel library using make."""
print("Building kernel library...")
# Check if Makefile.local exists, create it if not
makefile_local = Path("Makefile.local")
if not makefile_local.exists():
print("Creating Makefile.local...")
subprocess.check_call("./rebuild.sh --onlyconf", shell=True)
# Build the kernel library
try:
subprocess.check_call("make -C kernel", shell=True)
except subprocess.CalledProcessError as e:
print(f"Failed to build kernel library: {e}")
print("You may need to run './rebuild.sh' to configure the build properly.")
sys.exit(1)
def read_from_makefile(field):
"""Read build variables from kernel/Makefile."""
try:
makefile_defs = subprocess.getoutput("make -C kernel printvariables | grep '='").splitlines()
data = [line for line in makefile_defs if line.startswith(field)]
if not data:
print(f"Warning: Could not find {field} in Makefile variables")
return []
data = data[0]
data = '='.join(data.split('=')[1:])
data = data.strip()
data = [arg for arg in data.split(' ') if arg.strip()]
return data
except Exception as e:
print(f"Warning: Failed to read {field} from Makefile: {e}")
return []
def get_extension_modules():
"""Configure and return Cython extension modules."""
# Install system dependencies first
install_system_dependencies()
# Ensure dependencies are available
ensure_parallel_hashmap()
build_kernel_library()
# Read build configuration from Makefile
extra_compile_args = read_from_makefile("CXXFLAGS")
extra_link_args = read_from_makefile("LDFLAGS") + read_from_makefile("LIBADD")
# Fallback compile args if Makefile reading fails
if not extra_compile_args:
extra_compile_args = [
"-fPIC", "-Ofast", "-march=native", "-ftree-vectorize",
"-funroll-loops", "-std=c++17", "-pthread", "-Wall", "-Wextra"
]
if not extra_link_args:
extra_link_args = ["-shared", "-pthread", "-lpthread"]
# Library path for libG6K.so
kernel_lib_path = os.path.abspath("kernel")
extra_link_args.extend([f"-L{kernel_lib_path}", f"-Wl,-rpath={kernel_lib_path}"])
kwds = {
"language": "c++",
"extra_compile_args": extra_compile_args,
"extra_link_args": extra_link_args,
"libraries": ["gmp", "pthread", "G6K"],
"library_dirs": [kernel_lib_path],
"include_dirs": [numpy.get_include(), "parallel-hashmap", "kernel"],
"runtime_library_dirs": [kernel_lib_path]
}
extensions = [
Extension("g6k.siever", ["g6k/siever.pyx"], **kwds),
Extension("g6k.siever_params", ["g6k/siever_params.pyx"], **kwds)
]
return cythonize(
extensions,
compiler_directives={
'binding': True,
'embedsignature': True,
'language_level': 3
}
)
def load_rebuild_config():
"""Load configuration from rebuild.sh if available."""
config = {
'MAX_SIEVING_DIM': 128,
'GPUVECNUM': 65536,
'EXTRAFLAGS': '',
'HAVE_CUDA': None, # Auto-detect if not specified
'CUDA_PATH': '/usr/local/cuda'
}
try:
config_path = os.environ.get('G6K_COMPILE_CONFIG')
if config_path:
spec = importlib.util.spec_from_file_location('g6k_compile_config', config_path)
compile_config = importlib.util.module_from_spec(spec)
spec.loader.exec_module(compile_config)
else:
import compile_config
rebuild_config = compile_config.REBUILD_CONFIG
config.update(rebuild_config)
print(f"Using rebuild.sh configuration: MAX_SIEVING_DIM={config['MAX_SIEVING_DIM']}")
except ImportError:
print("No rebuild.sh configuration found, using defaults")
return config
def cuda_paths(cuda_path):
"""Return CUDA include/lib/stub paths for regular and conda layouts."""
cuda_root = Path(cuda_path)
target = cuda_root / "targets" / f"{os.uname().machine}-linux"
include_dir = target / "include" if (target / "include").exists() else cuda_root / "include"
library_dir = target / "lib" if (target / "lib").exists() else cuda_root / "lib64"
stub_dir = library_dir / "stubs"
return str(include_dir), str(library_dir), str(stub_dir)
def compile_cuda_objects(config=None):
"""Compile CUDA objects if CUDA is available."""
if config is None:
config = load_rebuild_config()
cuda_obj_path = 'cuda/GPUStreamGeneral.o'
cuda_src_path = 'cuda/GPUStreamGeneral.cu'
if not os.path.exists(cuda_src_path):
return None
# Check if we need to recompile
if not os.path.exists(cuda_obj_path) or \
os.path.getmtime(cuda_src_path) > os.path.getmtime(cuda_obj_path):
print("Compiling CUDA objects...")
max_sieving_dim = config.get('MAX_SIEVING_DIM', 128)
gpuvecnum = config.get('GPUVECNUM', 65536)
cuda_path = config.get('CUDA_PATH', '/usr/local/cuda')
cuda_include_dir, _, _ = cuda_paths(cuda_path)
cuda_defines = [flag for flag in config.get('EXTRAFLAGS', '').split()
if flag.startswith('-D')]
for flag in (f'-DMAX_SIEVING_DIM={max_sieving_dim}',
f'-DGPUVECNUM={gpuvecnum}', '-DHAVE_CUDA'):
if flag not in cuda_defines:
cuda_defines.append(flag)
nvcc_cmd = [
f'{cuda_path}/bin/nvcc',
'-ccbin', 'g++',
'-Xcompiler', '-fPIC',
'-Xcompiler', '-Ofast',
'-Xcompiler', '-march=native',
'-Xcompiler', '-mno-amx-tile',
'-Xcompiler', '-mno-amx-int8',
'-Xcompiler', '-mno-amx-bf16',
'-Xcompiler', '-pthread',
'-Xcompiler', '-Wall',
'-Xcompiler', '-Wextra',
*cuda_defines,
'-std=c++17',
'-O3',
'--use_fast_math',
'-Xptxas=-O3,-dlcm=ca',
'-diag-suppress', '191',
'-gencode', 'arch=compute_89,code=sm_89',
'-gencode', 'arch=compute_89,code=compute_89',
'-lineinfo',
f'-I{cuda_include_dir}',
'-Iparallel-hashmap',
'-c', cuda_src_path,
'-o', cuda_obj_path
]
try:
subprocess.run(nvcc_cmd, check=True, cwd='.')
print(f"Successfully compiled {cuda_obj_path}")
return cuda_obj_path
except subprocess.CalledProcessError as e:
print(f"Failed to compile CUDA objects: {e}")
return None
else:
print(f"CUDA object {cuda_obj_path} is up to date")
return cuda_obj_path
def get_ext_modules():
"""Get extension modules after setting up dependencies."""
ext_modules = []
# Check that required Cython source files exist
required_files = [
'g6k/siever.pyx',
'g6k/siever_params.pyx'
]
missing_files = [f for f in required_files if not os.path.exists(f)]
if missing_files:
print(f"Error: Missing required Cython source files: {missing_files}")
return []
else:
print(f"✅ Found required Cython source files: {required_files}")
try:
# Load configuration from rebuild.sh if available
config = load_rebuild_config()
# Check if we should build CUDA extensions
if config.get('HAVE_CUDA') == 1:
build_cuda = True
elif config.get('HAVE_CUDA') == 0:
build_cuda = False
else:
# Auto-detect CUDA
build_cuda = os.path.exists('/usr/local/cuda') and shutil.which('nvcc')
cuda_obj_path = None
if build_cuda:
# Compile CUDA objects with configuration
cuda_obj_path = compile_cuda_objects(config)
if not cuda_obj_path:
print("Failed to compile CUDA objects, falling back to CPU-only")
build_cuda = False
print(f"Building G6K GPU Tensor extensions (CUDA: {'enabled' if build_cuda else 'disabled'})")
cuda_include_dir, cuda_library_dir, cuda_stub_dir = cuda_paths(config.get('CUDA_PATH', '/usr/local/cuda'))
# Add cysignals include directory
cysignals_include = None
try:
import cysignals
cysignals_include = os.path.dirname(cysignals.__file__)
except ImportError:
pass
include_dirs = [
'kernel',
'parallel-hashmap',
numpy.get_include(),
]
if cysignals_include:
include_dirs.append(cysignals_include)
if build_cuda:
include_dirs.extend([
'cuda',
cuda_include_dir
])
# Build main siever extension
sources = ['g6k/siever.pyx']
# Add all kernel files including GPU sieve
kernel_sources = [
'kernel/bgj1_sieve.cpp',
'kernel/control.cpp',
'kernel/cpuperf.cpp',
'kernel/gpu_sieve.cpp',
'kernel/params.cpp',
'kernel/sieving.cpp',
'kernel/triple_sieve.cpp',
'kernel/triple_sieve_mt.cpp'
]
sources += kernel_sources
# Add CUDA object as extra link arg if available
extra_link_args = ['-lpthread', '-lm']
if build_cuda and cuda_obj_path and os.path.exists(cuda_obj_path):
extra_link_args.append(cuda_obj_path)
# Add CUDA-specific linker flags
extra_link_args.extend([
f'-L{cuda_library_dir}',
'-L/usr/lib/wsl/lib',
f'-L{cuda_stub_dir}',
f'-Wl,-rpath,{cuda_library_dir}',
'-Wl,-rpath,/usr/lib/wsl/lib',
'-lcudart',
'-lcuda',
'-lcublas',
'-lcurand'
])
# Libraries and library directories
libraries = ['pthread', 'm']
library_dirs = ['/usr/lib/x86_64-linux-gnu']
if build_cuda:
libraries.extend(['cuda', 'cudart', 'cublas', 'curand'])
library_dirs.extend([
cuda_library_dir,
'/usr/lib/wsl/lib',
cuda_stub_dir
])
# Define macros from configuration
define_macros = []
max_sieving_dim = config.get('MAX_SIEVING_DIM', 128)
gpuvecnum = config.get('GPUVECNUM', 65536)
define_macros.extend([
('MAX_SIEVING_DIM', str(max_sieving_dim)),
('GPUVECNUM', str(gpuvecnum))
])
if build_cuda:
define_macros.extend([
('G6K_CUDA', '1'),
('HAVE_CUDA', '1')
])
# Add extra flags from rebuild.sh
extra_flags = config.get('EXTRAFLAGS', '')
if extra_flags:
for flag in extra_flags.split():
if flag.startswith('-D'):
flag_def = flag[2:] # Remove -D prefix
if '=' in flag_def:
name, value = flag_def.split('=', 1)
define_macros.append((name, value))
else:
define_macros.append((flag_def, '1'))
# Add runtime library paths for CUDA
runtime_library_dirs = []
if build_cuda:
runtime_library_dirs.extend([
cuda_library_dir,
'/usr/lib/wsl/lib',
])
ext_modules.append(Extension(
'g6k.siever',
sources=sources,
libraries=libraries,
library_dirs=library_dirs,
runtime_library_dirs=runtime_library_dirs,
language='c++',
include_dirs=include_dirs,
extra_compile_args=['-std=c++17', '-O3', '-march=native'],
extra_link_args=extra_link_args,
define_macros=define_macros
))
# Build siever_params with same configuration as siever
print("Configuring siever_params extension...")
ext_modules.append(Extension(
'g6k.siever_params',
sources=['g6k/siever_params.pyx'],
include_dirs=include_dirs,
libraries=libraries,
library_dirs=library_dirs,
runtime_library_dirs=runtime_library_dirs,
language='c++',
extra_compile_args=['-std=c++17', '-O3', '-march=native'],
extra_link_args=extra_link_args,
define_macros=define_macros
))
print(f"Successfully configured {len(ext_modules)} extensions:")
for ext in ext_modules:
print(f" - {ext.name}")
except Exception as e:
print(f"Error: Could not configure C++ extensions: {e}")
import traceback
traceback.print_exc()
print("This will likely cause import errors!")
# Don't just silently continue - we need these extensions
# Try to build minimal standalone extensions
try:
print("Attempting minimal standalone extension build...")
# Basic include directories
basic_includes = [
numpy.get_include(),
'kernel'
]
# Try to add cysignals if available
try:
import cysignals
basic_includes.append(os.path.dirname(cysignals.__file__))
except ImportError:
print("Warning: cysignals not available")
ext_modules = [
Extension(
'g6k.siever_params',
sources=['g6k/siever_params.pyx'],
include_dirs=basic_includes,
language='c++',
extra_compile_args=['-std=c++17', '-O2']
),
Extension(
'g6k.siever',
sources=['g6k/siever.pyx'],
include_dirs=basic_includes,
language='c++',
extra_compile_args=['-std=c++17', '-O2']
)
]
print(f"Minimal standalone extensions configured: {[ext.name for ext in ext_modules]}")
except Exception as fallback_e:
print(f"Even minimal fallback failed: {fallback_e}")
import traceback
traceback.print_exc()
print("\n" + "="*50)
print("CRITICAL ERROR: Cannot build any extensions!")
print("This will cause ModuleNotFoundError at runtime!")
print("="*50 + "\n")
# Return empty list - setup will continue but runtime will fail
ext_modules = []
# Apply cythonize to all extensions
if ext_modules:
print(f"Applying cythonize to {len(ext_modules)} extensions...")
try:
ext_modules = cythonize(
ext_modules,
compiler_directives={
'binding': True,
'embedsignature': True,
'language_level': 3
},
build_dir="build" # Specify build directory
)
print("Cythonize completed successfully")
except Exception as e:
print(f"Cythonize failed: {e}")
import traceback
traceback.print_exc()
raise
else:
print("Warning: No extensions to build!")
return ext_modules
if __name__ == "__main__":
print("Starting G6K GPU Tensor setup...")
ext_mods = get_ext_modules()
print(f"Final extension modules: {[ext.name if hasattr(ext, 'name') else str(ext) for ext in ext_mods]}")
setup(
use_scm_version=True,
cmdclass={'build_ext': CustomBuildExt},
ext_modules=ext_mods,
zip_safe=False
)