pax_global_header 0000666 0000000 0000000 00000000064 13451323157 0014516 g ustar 00root root 0000000 0000000 52 comment=3f297889563bcbec671982c655996ccff63fa253
leela-zero-0.17/ 0000775 0000000 0000000 00000000000 13451323157 0013504 5 ustar 00root root 0000000 0000000 leela-zero-0.17/.gitignore 0000664 0000000 0000000 00000000276 13451323157 0015501 0 ustar 00root root 0000000 0000000 leelaz
*.o
*.d
.vscode/settings.json
training/tf/leelalogs
training/tf/checkpoint
training/tf/venv
leelaz-model*
*.orig
leelaz_opencl_tuning
/build-autogtp-*
/build-validation-*
.vs/
build/
leela-zero-0.17/.gitmodules 0000664 0000000 0000000 00000000261 13451323157 0015660 0 ustar 00root root 0000000 0000000 [submodule "gtest"]
path = gtest
url = https://github.com/google/googletest.git
[submodule "src/Eigen"]
path = src/Eigen
url = https://github.com/eigenteam/eigen-git-mirror
leela-zero-0.17/.travis.yml 0000664 0000000 0000000 00000003240 13451323157 0015614 0 ustar 00root root 0000000 0000000 sudo: required
language: cpp
services:
- docker
before_install:
- docker pull ubuntu:16.04
- docker build -f Dockerfiles/Dockerfile.base -t leela-zero:base .
jobs:
include:
- stage: test
script:
- docker build -f Dockerfiles/Dockerfile.gpu -t leela-zero:gpu .
- docker run leela-zero:gpu
- script:
- docker build -f Dockerfiles/Dockerfile.gpu-blas -t leela-zero:gpu-blas .
- docker run leela-zero:gpu-blas
- script:
- docker build -f Dockerfiles/Dockerfile.cpu -t leela-zero:cpu .
- docker run leela-zero:cpu
- script:
- docker build -f Dockerfiles/Dockerfile.cpu-blas -t leela-zero:cpu-blas .
- docker run leela-zero:cpu-blas
- script:
- docker build -f Dockerfiles/Dockerfile.tests -t leela-zero:tests .
- docker run leela-zero:tests
- script:
- docker build -f Dockerfiles/Dockerfile.tests-blas -t leela-zero:tests-blas .
- docker run leela-zero:tests-blas
- stage: style
before_install:
script: find . -regex ".*\.\(cpp\|h\|hpp\)" -not -regex ".*moc_.*.cpp" -not -path "./gtest/*" -not -path "./training/*" -not -path "./src/half/*" -not -path "./src/CL/*" -not -path "./src/Eigen/*" | xargs python2 scripts/cpplint.py --filter=-build/c++11,-build/include,-build/include_order,-build/include_what_you_use,-build/namespaces,-readability/braces,-readability/casting,-readability/fn_size,-readability/namespace,-readability/todo,-runtime/explicit,-runtime/indentation_namespace,-runtime/int,-runtime/references,-whitespace/blank_line,-whitespace/braces,-whitespace/comma,-whitespace/comments,-whitespace/empty_loop_body,-whitespace/line_length,-whitespace/semicolon
leela-zero-0.17/AUTHORS 0000664 0000000 0000000 00000001356 13451323157 0014561 0 ustar 00root root 0000000 0000000 Gian-Carlo Pascutto
Seth Troisi
Henrik Forstén
TFiFiE
Junhee Yoo
Marco Calignano
Andy Olsen
Hersmunch
Bood Qian
Peter Wen
ywrt
Arseny Krasutsky
earthengine
Jonathan Roy
Mankit Pong
michael
Barry G Becker
Junyan Xu
Maks Kolman
kuba97531
Antti Korhonen
Chin-Chang Yang
Xingcan LAN
bittsitt
tux3
5525345551
Adrian Petrescu
Akita Noek
Alderi-Tokori
Alexander Taylor
Ancalagon
Ashley Griffiths
Barry Becker
Ed Lee
Eddh
F. Huizinga
FFLaguna
Jiannan Liu
Joe Ren
LL145
Mark Andrew Gerads
Nate
OmnipotentEntity
Przemek Wesołek
Sebastian H
Shen-Ta Hsieh(BestSteve)
Virgile Andreani
Ximin Luo
ZenStone
Zhenzhen Zhan
afalturki
betterworld
cheshirecats
dbosst
fohristiwhirl
gaieepo
ncaq
tterava
wonderingabout
zediir
zliu1022
Пахотин Иван
Google LLC
leela-zero-0.17/CMakeLists.txt 0000664 0000000 0000000 00000013550 13451323157 0016250 0 ustar 00root root 0000000 0000000 # This file is part of Leela Zero.
# Copyright (C) 2017 Marco Calignano
# Copyright (C) 2017-2019 Gian-Carlo Pascutto and contributors
# Leela Zero is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Leela Zero is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with Leela Zero. If not, see .
cmake_minimum_required(VERSION 3.1)
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake/Modules/")
include(GNUInstallDirs)
project(leelaz)
add_subdirectory(gtest EXCLUDE_FROM_ALL) # We don't want to install gtest, exclude it from `all`
# Required Packages
set(Boost_MIN_VERSION "1.58.0")
set(Boost_USE_MULTITHREADED ON)
find_package(Boost 1.58.0 REQUIRED program_options filesystem)
find_package(Threads REQUIRED)
find_package(ZLIB REQUIRED)
find_package(OpenCL REQUIRED)
# We need OpenBLAS for now, because we make some specific
# calls. Ideally we'd use OpenBLAS is possible and fall back to
# not doing those calls if it's not present.
if(NOT APPLE)
set(BLA_VENDOR OpenBLAS)
endif()
if(USE_BLAS)
message(STATUS "Looking for system BLAS/OpenBLAS library.")
find_package(BLAS REQUIRED)
find_path(BLAS_INCLUDE_DIRS openblas_config.h
/usr/include
/usr/local/include
/usr/include/openblas
/opt/OpenBLAS/include
/usr/include/x86_64-linux-gnu
$ENV{BLAS_HOME}/include)
add_definitions(-DUSE_BLAS)
else()
message(STATUS "Using built-in matrix library.")
endif()
find_package(Qt5Core)
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED on)
# See if we can set optimization flags as expected.
if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
set(GccSpecificFlags 1)
elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "AppleClang")
set(GccSpecificFlags 1)
elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
set(GccSpecificFlags 1)
elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Intel")
set(GccSpecificFlags 0)
elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
set(GccSpecificFlags 0)
endif()
if(NOT CMAKE_CONFIGURATION_TYPES AND NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE RELEASE)
endif(NOT CMAKE_CONFIGURATION_TYPES AND NOT CMAKE_BUILD_TYPE)
if(GccSpecificFlags)
set(GCC_COMPILE_FLAGS "-Wall -Wextra -ffast-math -flto -march=native")
set(GCC_DISABLED_WARNING_COMPILE_FLAGS "-Wno-ignored-attributes -Wno-maybe-uninitialized \
-Wno-mismatched-tags")
set(GCC_FLAGS "${GCC_COMPILE_FLAGS} ${GCC_DISABLED_WARNING_COMPILE_FLAGS}")
set(CMAKE_CXX_FLAGS_DEBUG "${GCC_FLAGS} -g -Og")
set(CMAKE_CXX_FLAGS_RELEASE "${GCC_FLAGS} -g -O3 -DNDEBUG")
set(CMAKE_EXE_LINKER_FLAGS "-flto -g")
endif(GccSpecificFlags)
if(USE_CPU_ONLY)
add_definitions(-DUSE_CPU_ONLY)
endif()
if(USE_HALF)
add_definitions(-DUSE_HALF)
endif()
set(IncludePath "${CMAKE_CURRENT_SOURCE_DIR}/src" "${CMAKE_CURRENT_SOURCE_DIR}/src/Eigen")
set(SrcPath "${CMAKE_CURRENT_SOURCE_DIR}/src")
include_directories(${IncludePath})
include_directories(${Boost_INCLUDE_DIRS})
include_directories(${OpenCL_INCLUDE_DIRS})
include_directories(${ZLIB_INCLUDE_DIRS})
if((UNIX AND NOT APPLE) OR WIN32)
include_directories(${BLAS_INCLUDE_DIRS})
endif()
if(APPLE)
include_directories("/System/Library/Frameworks/Accelerate.framework/Versions/Current/Headers")
endif()
set(leelaz_MAIN "${SrcPath}/Leela.cpp")
file(GLOB leelaz_SRC "${SrcPath}/*.cpp")
list(REMOVE_ITEM leelaz_SRC ${leelaz_MAIN})
# Reuse for leelaz and gtest
add_library(objs OBJECT ${leelaz_SRC})
add_executable(leelaz $ ${leelaz_MAIN})
target_link_libraries(leelaz ${Boost_LIBRARIES})
target_link_libraries(leelaz ${BLAS_LIBRARIES})
target_link_libraries(leelaz ${OpenCL_LIBRARIES})
target_link_libraries(leelaz ${ZLIB_LIBRARIES})
target_link_libraries(leelaz ${CMAKE_THREAD_LIBS_INIT})
install(TARGETS leelaz DESTINATION ${CMAKE_INSTALL_BINDIR})
if(Qt5Core_FOUND)
if(NOT Qt5Core_VERSION VERSION_LESS "5.3.0")
add_subdirectory(autogtp)
add_subdirectory(validation)
else()
message(WARNING "Qt ${Qt5Core_VERSION} is found but does not met required version 5.3.0, \
build target for `autogtp` and `validation` is disabled.")
endif()
else()
message(WARNING "Qt is not found, build for `autogtp` and `validation` is disabled")
endif()
# Google Test below
file(GLOB tests_SRC "${SrcPath}/tests/*.cpp")
add_executable(tests ${tests_SRC} $)
if(GccSpecificFlags)
target_compile_options(tests PRIVATE "-Wno-unused-variable")
endif()
target_link_libraries(tests ${Boost_LIBRARIES})
target_link_libraries(tests ${BLAS_LIBRARIES})
target_link_libraries(tests ${OpenCL_LIBRARIES})
target_link_libraries(tests ${ZLIB_LIBRARIES})
target_link_libraries(tests gtest_main ${CMAKE_THREAD_LIBS_INIT})
include(GetGitRevisionDescription)
git_describe(VERSION --tags)
string(REGEX REPLACE "^v([0-9]+)\\..*" "\\1" MAJOR_VERSION "${VERSION}")
string(REGEX REPLACE "^v[0-9]+\\.([0-9]+).*" "\\1" MINOR_VERSION "${VERSION}")
SET(CPACK_GENERATOR "DEB")
SET(CPACK_DEBIAN_PACKAGE_NAME "leelaz")
SET(CPACK_DEBIAN_PACKAGE_VERSION "${MAJOR_VERSION}.${MINOR_VERSION}")
SET(CPACK_DEBIAN_ARCHITECTURE ${CMAKE_SYSTEM_PROCESSOR})
SET(CPACK_DEBIAN_PACKAGE_MAINTAINER "Gian-Carlo Pascutto https://github.com/gcp/leela-zero")
SET(CPACK_DEBIAN_PACKAGE_DESCRIPTION "Go engine with no human-provided knowledge, modeled after the AlphaGo Zero paper.")
SET(CPACK_DEBIAN_PACKAGE_PRIORITY "optional")
SET(CPACK_DEBIAN_PACKAGE_SECTION "games")
SET(CPACK_DEBIAN_PACKAGE_SHLIBDEPS ON)
SET(CPACK_PACKAGE_FILE_NAME "${CMAKE_PROJECT_NAME}-${MAJOR_VERSION}.${MINOR_VERSION}")
INCLUDE(CPack)
leela-zero-0.17/CONTRIBUTING.md 0000664 0000000 0000000 00000017407 13451323157 0015746 0 ustar 00root root 0000000 0000000 # Contributing to Leela Zero
## C++ Usage
Leela Zero is written in C++14, and generally encourages writing in modern C++ style.
This means that:
* The code overwhelmingly uses Almost Always Auto style, and so should you.
* Prefer range based for and non-member (c)begin/(c)end.
* You can rely on boost 1.58.0 or later being present.
* Manipulation of raw pointers is to be avoided as much as possible.
* Prefer constexpr over defines or constants.
* Prefer "using" over typedefs.
* Prefer uniform initialization.
* Prefer default initializers for member variables.
* Prefer emplace_back and making use of move assignment.
* Aim for const-correctness. Prefer passing non-trivial parameters by const reference.
* Use header include guards, not #pragma once (pragma once is non-standard, has issues with detecting identical files, and is slower https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58770)
* config.h is always the first file included.
* Feel free to use templates, but remember that debugging obscure template metaprogramming bugs is not something people enjoy doing in their spare time.
* Using exceptions is allowed.
## Code Style
* Look at the surrounding code and the rest of the project!
* Indentation is 4 spaces. No tabs.
* public/private/protected access modifiers are de-indented
* Maximum line length is 80 characters. There are rare exceptions in the code, usually involving user-visible text strings.
* Ifs are always braced, with very rare exceptions when everything fits on one line and doing it properly makes the code less readable.
* The code generally avoids any pointer passing and allows non-const references for parameters. Still, for new code it should be preferred to a) put input parameters first b) use return values over output parameters.
* Function arguments that wrap are aligned.
* Member variables in a class have an m_ prefix and are private. Members of POD structs don't and aren't.
* Constants and enum values are ALL_CAPS.
* Variables are lowercase.
* Function names are underscore_case.
* Classes are CamelCase.
* Comments are preferably full sentences with proper capitalization and a period.
* Split the includes list into config.h, standard headers and our headers.
If something is not addressed here or there is no similar code, the Google C++ Style Guide is always a good reference.
We might move to enforce clang-format at some point.
## Adding dependencies
C++ does not quite have the package systems JavaScript and Rust have, so some restraint should be excercised when adding dependencies. Dependencies typically complicate the build for new contributors, especially on Windows, and reliance on specific, new versions can be a nuisance on Unix based systems.
The restraints on modern header-only libraries are significantly less because they avoid most of the above problems.
If a library is not mature and well-supported on Windows, Linux *and* macOS, you do not want it.
This is not an excuse to re-invent the wheel.
## Upgrading dependencies
The code and dependencies should target the latest stable versions of Visual Studio/MSVC, and the latest stable/LTS releases of common Linux distros, with some additional delay as not everyone will be able to upgrade to a new stable/LTS right away.
For example, upgrading to C++17 or boost 1.62.0 (oldest version in a Debian stable or Ubuntu LTS release) can be considered if there's a compelling use case and/or we can confirm it is supported on all platforms we reasonably target.
## Merging contributions
Contributions come in the form of pull requests against the "next" branch.
They are rebased or squashed on top of the next branch, so the history will stay linear, i.e. no merge commits.
Commit messages follow Linux kernel style: a summary phrase that is no more than 70-75 characters (but preferably <50) and describes both what the patch changes, as well as why the patch might be necessary.
If the patch is to a specific subsystem (AutoGTP, Validation, ...) then prefix the summary by that subsystem (e.g. AutoGTP: ...).
This is followed by a blank line, and a description that is wrapped at 72 characters. Good patch descriptions can be large time savers when someone has to bugfix the code afterwards.
The end of the commit message should mention which (github) issue the patch fixes, if any, and the pull request it belongs to.
Patches need to be reviewed before merging. Try to find the person who worked on the code last, or who has done work in nearby code (git blame is your friend, and this is why we write proper commit messages...). With some luck that is someone with write access to the repository. If not, you'll have to ping someone who does.
Experience says that the majority of the pull requests won't live up to this ideal, which means that maintainers will have to squash patch series and clean up the commit message to be coherent before merging.
If you are a person with write access to the repo, and are about to merge a commit, ask yourself the following question: am I confident enough that I understand this code, so that I can and am willing to go in and fix it if it turns out to be necessary? If the answer to this question is no, then do not merge the code. Not merging a contribution (quickly) is annoying for the individual contributor. Merging a bad contribution is annoying for everyone who wants to contribute now and in the future.
If a contributor can't be bothered to fix up the trailing whitespace in their patch, odds are they aren't going to be willing to fix the threading bug it introduces either.
## "Improvements" and Automagic
Improvements to the engine that can affect strength should include supporting data. This means no-regression tests for functional changes, and a proof of strength improvement for things which are supposed to increase strength.
The tools in the validation directory are well-fit for this purpose, as
is the python tool "ringmaster".
The number of configurable options should be limited where possible. If it is not possible for the author to make rules of thumb for suitable values for those options, then the majority of users have no hope of getting them right, and may mistakenly make the engine weaker. If you must introduce new ones, consider limiting their exposure to developers only via USE_TUNER and set a good default for them.
## GTP Extensions
GTP makes it possible to connect arbitrary engines to arbitrary interfaces.
Unfortunately GTP 2 isn't extensive enough to realistically fit all needs of analysis GUIs, which means we have had to extend it. The lack of standardization here means that Go software is continously catching up to the chess world, especially after UCI was introduced. We should aim to make this situation better, not worse.
This means that extensions have the possibility of outliving Leela Zero (or any GUIs) provided they are well thought out.
It makes sense to be thoughtful here, consider the responsibilities of both GUI and engine, and try to come up with flexible building blocks rather than a plethora of commands for very specific use cases.
Experience and previous discussions can help understanding:
* lz-analyze "avoid" and "allow" were added in pull request [#1949](https://github.com/leela-zero/leela-zero/pull/1949).
* lz-analyze got a side-to-move option in pull request [#1872](https://github.com/leela-zero/leela-zero/pull/1872) and [#1642](https://github.com/leela-zero/leela-zero/pull/1642).
* lz-analyze got a "prior" tag in pull request [#1836](https://github.com/leela-zero/leela-zero/pull/1836).
* lz-analyze was added in pull request [#1388](https://github.com/leela-zero/leela-zero/pull/1388).
* lz-setoption was added in pull request [#1741](https://github.com/leela-zero/leela-zero/pull/1741).
* Pull request [#2170](https://github.com/leela-zero/leela-zero/pull/2170) has some discussion regarding how to navigate SGF
files that were parsed by the engine via GTP.
leela-zero-0.17/COPYING 0000664 0000000 0000000 00000104515 13451323157 0014545 0 ustar 00root root 0000000 0000000 GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
leela-zero-0.17/Dockerfiles/ 0000775 0000000 0000000 00000000000 13451323157 0015736 5 ustar 00root root 0000000 0000000 leela-zero-0.17/Dockerfiles/Dockerfile.base 0000664 0000000 0000000 00000000465 13451323157 0020646 0 ustar 00root root 0000000 0000000 FROM ubuntu:16.04
# Install
RUN apt-get -qq update
RUN apt-get install -y cmake g++
RUN apt-get install -y libboost-all-dev libopenblas-dev opencl-headers ocl-icd-libopencl1 ocl-icd-opencl-dev zlib1g-dev
RUN apt-get install -y qt5-default qt5-qmake
RUN mkdir -p /src/build/
COPY . /src/
WORKDIR /src/build/
leela-zero-0.17/Dockerfiles/Dockerfile.cpu 0000664 0000000 0000000 00000000214 13451323157 0020513 0 ustar 00root root 0000000 0000000 FROM leela-zero:base
# CPU build
RUN CXX=g++ CC=gcc cmake -DUSE_CPU_ONLY=1 ..
CMD cmake --build . --target leelaz --config Release -- -j2
leela-zero-0.17/Dockerfiles/Dockerfile.cpu-blas 0000664 0000000 0000000 00000000231 13451323157 0021431 0 ustar 00root root 0000000 0000000 FROM leela-zero:base
# CPU build
RUN CXX=g++ CC=gcc cmake -DUSE_CPU_ONLY=1 -DUSE_BLAS=1 ..
CMD cmake --build . --target leelaz --config Release -- -j2
leela-zero-0.17/Dockerfiles/Dockerfile.gpu 0000664 0000000 0000000 00000000173 13451323157 0020523 0 ustar 00root root 0000000 0000000 FROM leela-zero:base
# GPU build
RUN CXX=g++ CC=gcc cmake ..
CMD cmake --build . --target leelaz --config Release -- -j2
leela-zero-0.17/Dockerfiles/Dockerfile.gpu-blas 0000664 0000000 0000000 00000000210 13451323157 0021432 0 ustar 00root root 0000000 0000000 FROM leela-zero:base
# GPU build
RUN CXX=g++ CC=gcc cmake -DUSE_BLAS=1 ..
CMD cmake --build . --target leelaz --config Release -- -j2
leela-zero-0.17/Dockerfiles/Dockerfile.tests 0000664 0000000 0000000 00000000230 13451323157 0021064 0 ustar 00root root 0000000 0000000 FROM leela-zero:base
# CPU build
RUN CXX=g++ CC=gcc cmake -DUSE_CPU_ONLY=1 ..
RUN cmake --build . --target tests --config Release -- -j2
CMD ./tests
leela-zero-0.17/Dockerfiles/Dockerfile.tests-blas 0000664 0000000 0000000 00000000245 13451323157 0022011 0 ustar 00root root 0000000 0000000 FROM leela-zero:base
# CPU build
RUN CXX=g++ CC=gcc cmake -DUSE_CPU_ONLY=1 -DUSE_BLAS=1 ..
RUN cmake --build . --target tests --config Release -- -j2
CMD ./tests
leela-zero-0.17/FAQ.md 0000664 0000000 0000000 00000005716 13451323157 0014446 0 ustar 00root root 0000000 0000000 # Leela Zero常见问题解答 #
# Frequently Asked Questions about Leela Zero #
## 为什么网络不是每次都变强的 ##
## Why doesn't the network get stronger every time ##
从谷歌的论文中可以发现,AZ的网络强度也是有起伏的。而且现在只是在小规模测试阶段,发现问题也是很正常的。请保持耐心。
AZ also had this behavior, besides we're testing our approach right now. Please be patient.
## 为什么比较两个网络强弱时经常下十几盘就不下了 ##
## Why only dozens of games are played when comparing two networks ##
这里使用的是概率学意义上强弱,具体来说是SPRT在95%概率下任何一方有超过55%的胜率(ELO的35分),就认为有一方胜出了。谷歌的论文中是下满400盘的。唯一的区别是我们这里的Elo可能不是那么准确,网络的强弱还是可以确定的。
We use SPRT to decide if a newly trained network is better. A better network is only chosen if SPRT finds it's 95% confident that the new network has a 55% (boils down to 35 elo) win rate over the previous best network.
## 自对弈时产生的棋谱为什么下得很糟 ##
## Why the game generated during self-play contains quite a few bad moves ##
生成自对弈棋谱时,使用的MCTS模拟次数只有3200,还加入了噪声,这是为了增加随机性,之后的训练才有进步的空间。如果用图形界面(如sabiki)加载Leela Zero,并设置好参数与之对弈,你会发现它其实表现得并不赖。
The MCTS playouts of self-play games is only 3200, and with noise added (For randomness of each move thus training has something to learn from). If you load Leela Zero with Sabaki, you'll probably find it is actually not that weak.
## 有些自对弈对局非常短 ##
## Very short self-play games ends with White win?! ##
自对弈的增加了随机性,一旦黑棋在开始阶段选择pass,由于贴目的关系,白棋有很大概率也选择pass获胜。短对局由此产生。
This is expected. Due to randomness of self-play games, once Black choose to pass at the beginning, there is a big chance for White to pass too (7.5 komi advantage for White). See issue #198 for defailed explanation.
## 对局结果错误 ##
## Wrong score? ##
Leela Zero使用Tromp-Taylor规则(详见)。虽然与中国规则一样贴7.5目,但为计算方便,并不去除死子。因此,结果与使用中国规则计算可能有所不同。不过,不去除死子并不影响模型的训练结果,因为双方会将死子自行提掉。
Leela Zero uses Tromp-Taylor rules (see https://senseis.xmp.net/?TrompTaylorRules). Although its komi is 7.5 as in Chinese rule, for simplicity, Tromp-Taylor rules do not remove dead stones. Thus, the result may be different from that calcuated using Chinese rule. However, keeping dead stones does not affect training results because both players are expected to capture dead stones themselves.
leela-zero-0.17/README.md 0000664 0000000 0000000 00000036256 13451323157 0014777 0 ustar 00root root 0000000 0000000 [](https://travis-ci.org/leela-zero/leela-zero)
[](https://ci.appveyor.com/project/gcp/leela-zero-8arv1/branch/next)
# What
A Go program with no human provided knowledge. Using MCTS (but without
Monte Carlo playouts) and a deep residual convolutional neural network stack.
This is a fairly faithful reimplementation of the system described
in the Alpha Go Zero paper "[Mastering the Game of Go without Human Knowledge](https://deepmind.com/documents/119/agz_unformatted_nature.pdf)".
For all intents and purposes, it is an open source AlphaGo Zero.
# Wait, what?
If you are wondering what the catch is: you still need the network weights.
No network weights are in this repository. If you manage to obtain the
AlphaGo Zero weights, this program will be about as strong, provided you
also obtain a few Tensor Processing Units. Lacking those TPUs, I'd recommend
a top of the line GPU - it's not exactly the same, but the result would still
be an engine that is far stronger than the top humans.
# Gimme the weights
Recomputing the AlphaGo Zero weights will [take about 1700 years on commodity hardware](http://computer-go.org/pipermail/computer-go/2017-October/010307.html).
One reason for publishing this program is that we are running a public,
distributed effort to repeat the work. Working together, and especially
when starting on a smaller scale, it will take less than 1700 years to get
a good network (which you can feed into this program, suddenly making it strong).
# I want to help
## Using your own hardware
You need a PC with a GPU, i.e. a discrete graphics card made by NVIDIA or AMD,
preferably not too old, and with the most recent drivers installed.
It is possible to run the program without a GPU, but performance will be much
lower. If your CPU is not *very* recent (Haswell or newer, Ryzen or newer),
performance will be outright bad, and it's probably of no use trying to join
the distributed effort. But you can still play, especially if you are patient.
### Windows
Head to the Github releases page at https://github.com/leela-zero/leela-zero/releases,
download the latest release, unzip, and launch autogtp.exe. It will connect to
the server automatically and do its work in the background, uploading results
after each game. You can just close the autogtp window to stop it.
### macOS and Linux
Follow the instructions below to compile the leelaz and autogtp binaries in
the build subdirectory. Then run autogtp as explained in the
[contributing](#contributing) instructions below.
Contributing will start when you run autogtp.
## Using a Cloud provider
Many cloud companies offer free trials (or paid solutions, not discussed here)
that are usable for helping the leela-zero project.
There are community maintained instructions available here:
* [Running Leela Zero client on a Tesla V100 GPU for free (Google Cloud Free Trial)](https://docs.google.com/document/d/1P_c-RbeLKjv1umc4rMEgvIVrUUZSeY0WAtYHjaxjD64/edit?usp=sharing)
* [Running Leela Zero client on a Tesla V100 GPU for free (Microsoft Azure Cloud Free Trial)](https://docs.google.com/document/d/1DMpi16Aq9yXXvGj0OOw7jbd7k2A9LHDUDxxWPNHIRPQ/edit?usp=sharing)
# I just want to play with Leela Zero right now
Download the best known network weights file from [here](https://zero.sjeng.org/best-network), or, if you prefer a more human style,
a (weaker) network trained from human games [here](https://sjeng.org/zero/best_v1.txt.zip).
If you are on Windows, download an official release from [here](https://github.com/leela-zero/leela-zero/releases) and head to the [Usage](#usage-for-playing-or-analyzing-games)
section of this README.
If you are on Unix or macOS, you have to compile the program yourself. Follow
the compilation instructions below and then read the [Usage](#usage-for-playing-or-analyzing-games) section.
# Compiling AutoGTP and/or Leela Zero
## Requirements
* GCC, Clang or MSVC, any C++14 compiler
* Boost 1.58.x or later, headers and program_options, filesystem and system libraries (libboost-dev, libboost-program-options-dev and libboost-filesystem-dev on Debian/Ubuntu)
* zlib library (zlib1g & zlib1g-dev on Debian/Ubuntu)
* Standard OpenCL C headers (opencl-headers on Debian/Ubuntu, or at
https://github.com/KhronosGroup/OpenCL-Headers/tree/master/CL)
* OpenCL ICD loader (ocl-icd-libopencl1 on Debian/Ubuntu, or reference implementation at https://github.com/KhronosGroup/OpenCL-ICD-Loader)
* An OpenCL capable device, preferably a very, very fast GPU, with recent
drivers is strongly recommended (OpenCL 1.1 support is enough). Don't
forget to install the OpenCL driver if this part is packaged seperately
by the Linux distribution (e.g. nvidia-opencl-icd).
If you do not have a GPU, add the define "USE_CPU_ONLY", for example
by adding -DUSE_CPU_ONLY=1 to the cmake command line.
* Optional: BLAS Library: OpenBLAS (libopenblas-dev) or Intel MKL
* The program has been tested on Windows, Linux and macOS.
## Example of compiling - Ubuntu & similar
# Test for OpenCL support & compatibility
sudo apt install clinfo && clinfo
# Clone github repo
git clone https://github.com/leela-zero/leela-zero
cd leela-zero
git submodule update --init --recursive
# Install build depedencies
sudo apt install libboost-dev libboost-program-options-dev libboost-filesystem-dev opencl-headers ocl-icd-libopencl1 ocl-icd-opencl-dev zlib1g-dev
# Use a stand alone build directory to keep source dir clean
mkdir build && cd build
# Compile leelaz and autogtp in build subdirectory with cmake
cmake ..
cmake --build .
# Optional: test if your build works correctly
./tests
## Example of compiling - macOS
# Clone github repo
git clone https://github.com/leela-zero/leela-zero
cd leela-zero
git submodule update --init --recursive
# Install build depedencies
brew install boost cmake zlib
# Use a stand alone build directory to keep source dir clean
mkdir build && cd build
# Compile leelaz and autogtp in build subdirectory with cmake
cmake ..
cmake --build .
# Optional: test if your build works correctly
./tests
## Example of compiling - Windows
# Clone github repo
git clone https://github.com/leela-zero/leela-zero
cd leela-zero
git submodule update --init --recursive
cd msvc
Double-click the leela-zero2015.sln or leela-zero2017.sln corresponding
to the Visual Studio version you have.
# Build from Visual Studio 2015 or 2017
# Contributing
For Windows, you can use a release package, see ["I want to help"](#windows).
Unix and macOS, after finishing the compile and while in the build directory:
# Copy leelaz binary to autogtp subdirectory
cp leelaz autogtp
# Run AutoGTP to start contributing
./autogtp/autogtp
# Usage for playing or analyzing games
Leela Zero is not meant to be used directly. You need a graphical interface
for it, which will interface with Leela Zero through the GTP protocol.
The engine supports the [GTP protocol, version 2](https://www.lysator.liu.se/~gunnar/gtp/gtp2-spec-draft2/gtp2-spec.html).
[Lizzie](https://github.com/featurecat/lizzie/releases) is a client specifically
for Leela Zero which shows live search probilities, a win rate graph, and has
an automatic game analysis mode. Has binaries for Windows, Mac, and Linux.
[Sabaki](http://sabaki.yichuanshen.de/) is a very nice looking GUI with GTP 2
capability.
[LeelaSabaki](https://github.com/SabakiHQ/LeelaSabaki) is modified to
show variations and winning statistics in the game tree, as well as a heatmap
on the game board.
[GoReviewPartner](https://github.com/pnprog/goreviewpartner) is a tool for
automated review and analysis of games using bots (saved as .rsgf files),
Leela Zero is supported.
A lot of go software can interface to an engine via GTP,
so look around.
Add the --gtp commandline option on the engine command line to enable Leela
Zero's GTP support. You will need a weights file, specify that with the -w option.
All required commands are supported, as well as the tournament subset, and
"loadsgf". The full set can be seen with "list_commands". The time control
can be specified over GTP via the time\_settings command. The kgs-time\_settings
extension is also supported. These have to be supplied by the GTP 2 interface,
not via the command line!
# Weights format
The weights file is a text file with each line containing a row of coefficients.
The layout of the network is as in the AlphaGo Zero paper, but any number of
residual blocks is allowed, and any number of outputs (filters) per layer,
as long as the latter is the same for all layers. The program will autodetect
the amounts on startup. The first line contains a version number.
* Convolutional layers have 2 weight rows:
1) convolution weights
2) channel biases
* Batchnorm layers have 2 weight rows:
1) batchnorm means
2) batchnorm variances
* Innerproduct (fully connected) layers have 2 weight rows:
1) layer weights
2) output biases
The convolution weights are in [output, input, filter\_size, filter\_size]
order, the fully connected layer weights are in [output, input] order.
The residual tower is first, followed by the policy head, and then the value
head. All convolution filters are 3x3 except for the ones at the start of the policy and value head, which are 1x1 (as in the paper).
There are 18 inputs to the first layer, instead of 17 as in the paper. The
original AlphaGo Zero design has a slight imbalance in that it is easier
for the black player to see the board edge (due to how padding works in
neural networks). This has been fixed in Leela Zero. The inputs are:
```
1) Side to move stones at time T=0
2) Side to move stones at time T=-1 (0 if T=0)
...
8) Side to move stones at time T=-7 (0 if T<=6)
9) Other side stones at time T=0
10) Other side stones at time T=-1 (0 if T=0)
...
16) Other side stones at time T=-7 (0 if T<=6)
17) All 1 if black is to move, 0 otherwise
18) All 1 if white is to move, 0 otherwise
```
Each of these forms a 19 x 19 bit plane.
In the training/caffe directory there is a zero.prototxt file which contains a
description of the full 40 residual block design, in (NVIDIA)-Caffe protobuff
format. It can be used to set up nv-caffe for training a suitable network.
The zero\_mini.prototxt file describes a smaller 12 residual block case. The
training/tf directory contains the network construction in TensorFlow format,
in the tfprocess.py file.
Expert note: the channel biases seem redundant in the network topology
because they are followed by a batchnorm layer, which is supposed to normalize
the mean. In reality, they encode "beta" parameters from a center/scale
operation in the batchnorm layer, corrected for the effect of the batchnorm mean/variance adjustment. At inference time, Leela Zero will fuse the channel
bias into the batchnorm mean, thereby offsetting it and performing the center operation. This roundabout construction exists solely for backwards
compatibility. If this paragraph does not make any sense to you, ignore its
existence and just add the channel bias layer as you normally would, output
will be correct.
# Training
## Getting the data
At the end of the game, you can send Leela Zero a "dump\_training" command,
followed by the winner of the game (either "white" or "black") and a filename,
e.g:
dump_training white train.txt
This will save (append) the training data to disk, in the format described below,
and compressed with gzip.
Training data is reset on a new game.
## Supervised learning
Leela can convert a database of concatenated SGF games into a datafile suitable
for learning:
dump_supervised sgffile.sgf train.txt
This will cause a sequence of gzip compressed files to be generated,
starting with the name train.txt and containing training data generated from
the specified SGF, suitable for use in a Deep Learning framework.
## Training data format
The training data consists of files with the following data, all in text
format:
* 16 lines of hexadecimal strings, each 361 bits longs, corresponding to the
first 16 input planes from the previous section
* 1 line with 1 number indicating who is to move, 0=black, 1=white, from which
the last 2 input planes can be reconstructed
* 1 line with 362 (19x19 + 1) floating point numbers, indicating the search probabilities
(visit counts) at the end of the search for the move in question. The last
number is the probability of passing.
* 1 line with either 1 or -1, corresponding to the outcome of the game for the
player to move
## Running the training
For training a new network, you can use an existing framework (Caffe,
TensorFlow, PyTorch, Theano), with a set of training data as described above.
You still need to contruct a model description (2 examples are provided for
Caffe), parse the input file format, and outputs weights in the proper format.
There is a complete implementation for TensorFlow in the training/tf directory.
### Supervised learning with TensorFlow
This requires a working installation of TensorFlow 1.4 or later:
src/leelaz -w weights.txt
dump_supervised bigsgf.sgf train.out
exit
training/tf/parse.py train.out
This will run and regularly dump Leela Zero weight files to disk, as
well as snapshots of the learning state numbered by the batch number.
If interrupted, training can be resumed with:
training/tf/parse.py train.out leelaz-model-batchnumber
# Todo
- [ ] Further optimize Winograd transformations.
- [ ] Improve GPU batching in the search.
- [ ] Root filtering for handicap play.
- More backends:
- [ ] MKL-DNN based backend.
- [ ] CUDA specific version using cuDNN or cuBLAS.
- [ ] AMD specific version using MIOpen/ROCm.
# Related links
* Status page of the distributed effort:
https://zero.sjeng.org
* GUI and study tool for Leela Zero:
https://github.com/featurecat/lizzie
* Watch Leela Zero's training games live in a GUI:
https://github.com/fsparv/LeelaWatcher
* Original Alpha Go (Lee Sedol) paper:
https://storage.googleapis.com/deepmind-media/alphago/AlphaGoNaturePaper.pdf
* Alpha Go Zero paper:
https://deepmind.com/documents/119/agz_unformatted_nature.pdf
* Alpha Zero (Go, Chess, Shogi) paper:
https://arxiv.org/pdf/1712.01815.pdf
* AlphaGo Zero Explained In One Diagram:
https://medium.com/applied-data-science/alphago-zero-explained-in-one-diagram-365f5abf67e0
* Stockfish chess engine ported to Leela Zero framework:
https://github.com/LeelaChessZero/lczero
* Leela Chess Zero (chess optimized client)
https://github.com/LeelaChessZero/lc0
# License
The code is released under the GPLv3 or later, except for ThreadPool.h, cl2.hpp, half.hpp and the eigen and clblast_level3 subdirs, which have specific licenses (compatible with GPLv3) mentioned in those files.
Additional permission under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with NVIDIA Corporation's libraries from the
NVIDIA CUDA Toolkit and/or the NVIDIA CUDA Deep Neural
Network library and/or the NVIDIA TensorRT inference library
(or a modified version of those libraries), containing parts covered
by the terms of the respective license agreement, the licensors of
this Program grant you additional permission to convey the resulting
work.
leela-zero-0.17/appveyor.yml 0000664 0000000 0000000 00000002170 13451323157 0016074 0 ustar 00root root 0000000 0000000 version: '{build}'
image:
- Visual Studio 2015
- Visual Studio 2017
configuration: Release
platform: x64
matrix:
fast_finish: true
environment:
matrix:
- cmake_build: 1
- cmake_build: 1
features: USE_CPU_ONLY
run_tests: 1
- cmake_build: 1
features: USE_CPU_ONLY USE_BLAS
run_tests: 1
- msbuild: 1
skip_commits:
files:
- '**/*.md'
- '**/.gitignore'
- scripts/
- training/
- AUTHORS
- COPYING
for:
- matrix:
only:
- image: Visual Studio 2015
install:
- cmd: set MSVCDIR=msvc\VS2015
- cmd: echo %MSVCDIR%
- cmd: nuget restore %MSVCDIR% -PackagesDirectory msvc\packages
- matrix:
only:
- image: Visual Studio 2017
install:
- cmd: set MSVCDIR=msvc\VS2017
- cmd: echo %MSVCDIR%
- cmd: nuget restore %MSVCDIR% -PackagesDirectory msvc\packages
build_script:
- cmd: if "%cmake_build%"=="1" %MSVCDIR%\cmake_build.bat
- cmd: if "%msbuild%"=="1" git submodule update --init --recursive
- cmd: if "%msbuild%"=="1" msbuild /t:build %MSVCDIR%\leela-zero.vcxproj
test_script:
- cmd: if "%run_tests%"=="1" cd build && Release\tests.exe
cache: msvc\packages -> appveyor.yml
leela-zero-0.17/autogtp/ 0000775 0000000 0000000 00000000000 13451323157 0015167 5 ustar 00root root 0000000 0000000 leela-zero-0.17/autogtp/.gitignore 0000664 0000000 0000000 00000000267 13451323157 0017164 0 ustar 00root root 0000000 0000000 /Makefile
/.qmake.stash
/autogtp
/*.sgf
/*.gz
/moc_*.cpp
/moc_*.h
/autogtp.pro.user
# Weight files
/[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]*[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]
leela-zero-0.17/autogtp/CMakeLists.txt 0000664 0000000 0000000 00000000527 13451323157 0017733 0 ustar 00root root 0000000 0000000
cmake_minimum_required(VERSION 3.1)
add_executable(autogtp
Game.h Order.h Management.h Worker.h Job.h Result.h Console.h
Worker.cpp Management.cpp Job.cpp main.cpp Game.cpp Order.cpp)
set_target_properties(autogtp PROPERTIES AUTOMOC 1)
target_link_libraries(autogtp Qt5::Core)
install(TARGETS autogtp DESTINATION ${CMAKE_INSTALL_BINDIR})
leela-zero-0.17/autogtp/Console.h 0000664 0000000 0000000 00000003262 13451323157 0016745 0 ustar 00root root 0000000 0000000 /*
This file is part of Leela Zero.
Copyright (C) 2017-2018 Marco Calignano
Leela Zero is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Leela Zero is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Leela Zero. If not, see .
*/
#ifndef CONSOLE_H
#define CONSOLE_H
#include
#include
#include
#include "stdio.h"
#ifdef Q_OS_WIN
#include
#include
typedef QWinEventNotifier Notifier;
#else
#include
typedef QSocketNotifier Notifier;
#endif
class Console : public QObject
{
Q_OBJECT
public:
Console(QObject *parent = nullptr)
: QObject(parent),
#ifdef Q_OS_WIN
m_notifier(GetStdHandle(STD_INPUT_HANDLE)) {
#else
m_notifier(fileno(stdin), Notifier::Read) {
#endif
connect(&m_notifier, &Notifier::activated, this, &Console::readInput);
}
~Console() = default;
signals:
void sendQuit();
public slots:
void readInput() {
QTextStream qin(stdin);
QString line = qin.readLine();
if (line.contains("q")) {
emit sendQuit();
}
}
private:
Notifier m_notifier;
};
#endif // CONSOLE_H
leela-zero-0.17/autogtp/Game.cpp 0000664 0000000 0000000 00000035707 13451323157 0016560 0 ustar 00root root 0000000 0000000 /*
This file is part of Leela Zero.
Copyright (C) 2017-2018 Marco Calignano
Leela Zero is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Leela Zero is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Leela Zero. If not, see .
*/
#include
#include
#include
#include
#include
#include "Game.h"
Game::Game(const Engine& engine) :
QProcess(),
m_engine(engine),
m_isHandicap(false),
m_resignation(false),
m_blackToMove(true),
m_blackResigned(false),
m_passes(0),
m_moveNum(0)
{
m_fileName = QUuid::createUuid().toRfc4122().toHex();
}
bool Game::checkGameEnd() {
return (m_resignation ||
m_passes > 1 ||
m_moveNum > (19 * 19 * 2));
}
void Game::error(int errnum) {
QTextStream(stdout) << "*ERROR*: ";
switch (errnum) {
case Game::NO_LEELAZ:
QTextStream(stdout)
<< "No 'leelaz' binary found." << endl;
break;
case Game::PROCESS_DIED:
QTextStream(stdout)
<< "The 'leelaz' process died unexpected." << endl;
break;
case Game::WRONG_GTP:
QTextStream(stdout)
<< "Error in GTP response." << endl;
break;
case Game::LAUNCH_FAILURE:
QTextStream(stdout)
<< "Could not talk to engine after launching." << endl;
break;
default:
QTextStream(stdout)
<< "Unexpected error." << endl;
break;
}
}
bool Game::eatNewLine() {
char readBuffer[256];
// Eat double newline from GTP protocol
if (!waitReady()) {
error(Game::PROCESS_DIED);
return false;
}
auto readCount = readLine(readBuffer, 256);
if (readCount < 0) {
error(Game::WRONG_GTP);
return false;
}
return true;
}
bool Game::sendGtpCommand(QString cmd) {
write(qPrintable(cmd.append("\n")));
waitForBytesWritten(-1);
if (!waitReady()) {
error(Game::PROCESS_DIED);
return false;
}
char readBuffer[256];
int readCount = readLine(readBuffer, 256);
if (readCount <= 0 || readBuffer[0] != '=') {
QTextStream(stdout) << "GTP: " << readBuffer << endl;
error(Game::WRONG_GTP);
return false;
}
if (!eatNewLine()) {
error(Game::PROCESS_DIED);
return false;
}
return true;
}
void Game::checkVersion(const VersionTuple &min_version) {
write(qPrintable("version\n"));
waitForBytesWritten(-1);
if (!waitReady()) {
error(Game::LAUNCH_FAILURE);
exit(EXIT_FAILURE);
}
char readBuffer[256];
int readCount = readLine(readBuffer, 256);
//If it is a GTP comment just print it and wait for the real answer
//this happens with the winogard tuning
if (readBuffer[0] == '#') {
readBuffer[readCount-1] = 0;
QTextStream(stdout) << readBuffer << endl;
if (!waitReady()) {
error(Game::PROCESS_DIED);
exit(EXIT_FAILURE);
}
readCount = readLine(readBuffer, 256);
}
// We expect to read at last "=, space, something"
if (readCount <= 3 || readBuffer[0] != '=') {
QTextStream(stdout) << "GTP: " << readBuffer << endl;
error(Game::WRONG_GTP);
exit(EXIT_FAILURE);
}
QString version_buff(&readBuffer[2]);
version_buff = version_buff.simplified();
QStringList version_list = version_buff.split(".");
if (version_list.size() < 2) {
QTextStream(stdout)
<< "Unexpected Leela Zero version: " << version_buff << endl;
exit(EXIT_FAILURE);
}
if (version_list.size() < 3) {
version_list.append("0");
}
int versionCount = (version_list[0].toInt() - std::get<0>(min_version)) * 10000;
versionCount += (version_list[1].toInt() - std::get<1>(min_version)) * 100;
versionCount += version_list[2].toInt() - std::get<2>(min_version);
if (versionCount < 0) {
QTextStream(stdout)
<< "Leela version is too old, saw " << version_buff
<< " but expected "
<< std::get<0>(min_version) << "."
<< std::get<1>(min_version) << "."
<< std::get<2>(min_version) << endl;
QTextStream(stdout)
<< "Check https://github.com/gcp/leela-zero for updates." << endl;
exit(EXIT_FAILURE);
}
if (!eatNewLine()) {
error(Game::WRONG_GTP);
exit(EXIT_FAILURE);
}
}
bool Game::gameStart(const VersionTuple &min_version,
const QString &sgf,
const int moves) {
start(m_engine.getCmdLine());
if (!waitForStarted()) {
error(Game::NO_LEELAZ);
return false;
}
// This either succeeds or we exit immediately, so no need to
// check any return values.
checkVersion(min_version);
QTextStream(stdout) << "Engine has started." << endl;
//If there is an sgf file to start playing from then it will contain
//whether there is handicap in use. If there is no sgf file then instead,
//check whether there are any handicap commands to send (these fail
//if the board is not empty).
//Then send the rest of the GTP commands after any SGF has been loaded so
//that they can override any settings loaded from the SGF.
if (!sgf.isEmpty()) {
QFile sgfFile(sgf + ".sgf");
if (!sgfFile.exists()) {
QTextStream(stdout) << "Cannot find sgf file " << sgf << endl;
exit(EXIT_FAILURE);
}
sgfFile.open(QIODevice::Text | QIODevice::ReadOnly);
const auto sgfData = QTextStream(&sgfFile).readAll();
const auto re = QRegularExpression("HA\\[\\d+\\]");
const auto match = re.match(sgfData);
m_isHandicap = match.hasMatch();
sgfFile.close();
if (moves == 0) {
loadSgf(sgf);
} else {
loadSgf(sgf, moves);
}
setMovesCount(moves);
} else {
for (auto command : m_engine.m_commands.filter("handicap")) {
QTextStream(stdout) << command << endl;
if (!sendGtpCommand(command))
{
QTextStream(stdout) << "GTP failed on: " << command << endl;
exit(EXIT_FAILURE);
}
m_isHandicap = true;
m_blackToMove = false;
}
}
const auto re = QRegularExpression("^((?!handicap).)*$");
for (auto command : m_engine.m_commands.filter(re)) {
QTextStream(stdout) << command << endl;
if (!sendGtpCommand(command))
{
QTextStream(stdout) << "GTP failed on: " << command << endl;
exit(EXIT_FAILURE);
}
}
QTextStream(stdout) << "Starting GTP commands sent." << endl;
return true;
}
void Game::move() {
m_moveNum++;
QString moveCmd;
if (m_blackToMove) {
moveCmd = "genmove b\n";
} else {
moveCmd = "genmove w\n";
}
write(qPrintable(moveCmd));
waitForBytesWritten(-1);
}
void Game::setMovesCount(int moves) {
m_moveNum = moves;
//The game always starts at move 0 (GTP states that handicap stones are not part
//of the move history), so if there is no handicap then black moves on even
//numbered turns but if there is handicap then black moves on odd numbered turns.
m_blackToMove = (moves % 2) == (m_isHandicap ? 1 : 0);
}
bool Game::waitReady() {
while (!canReadLine() && state() == QProcess::Running) {
waitForReadyRead(-1);
}
// somebody crashed
if (state() != QProcess::Running) {
return false;
}
return true;
}
bool Game::readMove() {
char readBuffer[256];
int readCount = readLine(readBuffer, 256);
if (readCount <= 3 || readBuffer[0] != '=') {
error(Game::WRONG_GTP);
QTextStream(stdout) << "Error read " << readCount << " '";
QTextStream(stdout) << readBuffer << "'" << endl;
terminate();
return false;
}
// Skip "= "
m_moveDone = readBuffer;
m_moveDone.remove(0, 2);
m_moveDone = m_moveDone.simplified();
if (!eatNewLine()) {
error(Game::PROCESS_DIED);
return false;
}
if (readCount == 0) {
error(Game::WRONG_GTP);
}
QTextStream(stdout) << m_moveNum << " (";
QTextStream(stdout) << (m_blackToMove ? "B " : "W ") << m_moveDone << ") ";
QTextStream(stdout).flush();
if (m_moveDone.compare(QStringLiteral("pass"),
Qt::CaseInsensitive) == 0) {
m_passes++;
} else if (m_moveDone.compare(QStringLiteral("resign"),
Qt::CaseInsensitive) == 0) {
m_resignation = true;
m_blackResigned = m_blackToMove;
} else {
m_passes = 0;
}
return true;
}
bool Game::setMove(const QString& m) {
if (!sendGtpCommand(m)) {
return false;
}
m_moveNum++;
QStringList moves = m.split(" ");
if (moves.at(2)
.compare(QStringLiteral("pass"), Qt::CaseInsensitive) == 0) {
m_passes++;
} else if (moves.at(2)
.compare(QStringLiteral("resign"), Qt::CaseInsensitive) == 0) {
m_resignation = true;
m_blackResigned = (moves.at(1).compare(QStringLiteral("black"), Qt::CaseInsensitive) == 0);
} else {
m_passes = 0;
}
m_blackToMove = !m_blackToMove;
return true;
}
bool Game::nextMove() {
if (checkGameEnd()) {
return false;
}
m_blackToMove = !m_blackToMove;
return true;
}
bool Game::getScore() {
if (m_resignation) {
if (m_blackResigned) {
m_winner = QString(QStringLiteral("white"));
m_result = "W+Resign ";
QTextStream(stdout) << "Score: " << m_result << endl;
} else {
m_winner = QString(QStringLiteral("black"));
m_result = "B+Resign ";
QTextStream(stdout) << "Score: " << m_result << endl;
}
} else{
write("final_score\n");
waitForBytesWritten(-1);
if (!waitReady()) {
error(Game::PROCESS_DIED);
return false;
}
char readBuffer[256];
readLine(readBuffer, 256);
m_result = readBuffer;
m_result.remove(0, 2);
if (readBuffer[2] == 'W') {
m_winner = QString(QStringLiteral("white"));
} else if (readBuffer[2] == 'B') {
m_winner = QString(QStringLiteral("black"));
}
if (!eatNewLine()) {
error(Game::PROCESS_DIED);
return false;
}
QTextStream(stdout) << "Score: " << m_result;
}
if (m_winner.isNull()) {
QTextStream(stdout) << "No winner found" << endl;
return false;
}
QTextStream(stdout) << "Winner: " << m_winner << endl;
return true;
}
int Game::getWinner() {
if (m_winner.compare(QStringLiteral("white"), Qt::CaseInsensitive) == 0)
return Game::WHITE;
else
return Game::BLACK;
}
bool Game::writeSgf() {
return sendGtpCommand(qPrintable("printsgf " + m_fileName + ".sgf"));
}
bool Game::loadTraining(const QString &fileName) {
QTextStream(stdout) << "Loading " << fileName + ".train" << endl;
return sendGtpCommand(qPrintable("load_training " + fileName + ".train"));
}
bool Game::saveTraining() {
QTextStream(stdout) << "Saving " << m_fileName + ".train" << endl;
return sendGtpCommand(qPrintable("save_training " + m_fileName + ".train"));
}
bool Game::loadSgf(const QString &fileName) {
QTextStream(stdout) << "Loading " << fileName + ".sgf" << endl;
return sendGtpCommand(qPrintable("loadsgf " + fileName + ".sgf"));
}
bool Game::loadSgf(const QString &fileName, const int moves) {
QTextStream(stdout) << "Loading " << fileName + ".sgf with " << moves << " moves" << endl;
return sendGtpCommand(qPrintable("loadsgf " + fileName + ".sgf " + QString::number(moves + 1)));
}
void Game::fixSgfPlayer(QString& sgfData, const Engine& whiteEngine) {
QRegularExpression oldPlayer("PW\\[Human\\]");
QString playerName("PB[Leela Zero ");
QRegularExpression le("PB\\[Leela Zero \\S+ ");
QRegularExpressionMatch match = le.match(sgfData);
if (match.hasMatch()) {
playerName = match.captured(0);
}
playerName = "PW" + playerName.remove(0, 2);
playerName += whiteEngine.getNetworkFile().left(8);
playerName += "]";
sgfData.replace(oldPlayer, playerName);
}
void Game::fixSgfComment(QString& sgfData, const Engine& whiteEngine,
const bool isSelfPlay) {
QRegularExpression oldComment("(C\\[Leela Zero)( options:.*)\\]");
QString comment("\\1");
if (!isSelfPlay) {
comment += " Black";
}
comment += "\\2 Starting GTP commands:";
for (const auto command : m_engine.m_commands) {
comment += " " + command;
}
if (!isSelfPlay) {
comment += " White options:";
comment += whiteEngine.m_options + " " + whiteEngine.m_network;
comment += " Starting GTP commands:";
for (const auto command : whiteEngine.m_commands) {
comment += " " + command;
}
}
comment += "]";
comment.replace(QRegularExpression("\\s\\s+"), " ");
sgfData.replace(oldComment, comment);
}
void Game::fixSgfResult(QString& sgfData, const bool resignation) {
if (resignation) {
QRegularExpression oldResult("RE\\[B\\+.*\\]");
QString newResult("RE[B+Resign] ");
sgfData.replace(oldResult, newResult);
if (!sgfData.contains(newResult, Qt::CaseInsensitive)) {
QRegularExpression oldwResult("RE\\[W\\+.*\\]");
sgfData.replace(oldwResult, newResult);
}
QRegularExpression lastpass(";W\\[tt\\]\\)");
QString noPass(")");
sgfData.replace(lastpass, noPass);
}
}
bool Game::fixSgf(const Engine& whiteEngine, const bool resignation,
const bool isSelfPlay) {
QFile sgfFile(m_fileName + ".sgf");
if (!sgfFile.open(QIODevice::Text | QIODevice::ReadOnly)) {
return false;
}
QString sgfData = sgfFile.readAll();
fixSgfPlayer(sgfData, whiteEngine);
fixSgfComment(sgfData, whiteEngine, isSelfPlay);
fixSgfResult(sgfData, resignation);
sgfFile.close();
if (sgfFile.open(QFile::WriteOnly | QFile::Truncate)) {
QTextStream out(&sgfFile);
out << sgfData;
}
sgfFile.close();
return true;
}
bool Game::dumpTraining() {
return sendGtpCommand(
qPrintable("dump_training " + m_winner + " " + m_fileName + ".txt"));
}
bool Game::dumpDebug() {
return sendGtpCommand(
qPrintable("dump_debug " + m_fileName + ".debug.txt"));
}
void Game::gameQuit() {
write(qPrintable("quit\n"));
waitForFinished(-1);
}
leela-zero-0.17/autogtp/Game.h 0000664 0000000 0000000 00000007177 13451323157 0016225 0 ustar 00root root 0000000 0000000 /*
This file is part of Leela Zero.
Copyright (C) 2017-2018 Marco Calignano
Leela Zero is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Leela Zero is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Leela Zero. If not, see .
*/
#ifndef GAME_H
#define GAME_H
#include
#include
#include
using VersionTuple = std::tuple;
class Engine {
public:
Engine(const QString& network,
const QString& options,
const QStringList& commands = QStringList("time_settings 0 1 0"),
const QString& binary = QString("./leelaz")) :
m_binary(binary), m_options(options),
m_network(network), m_commands(commands) {
#ifdef WIN32
m_binary.append(".exe");
#endif
if (!QFileInfo::exists(m_binary)) {
m_binary.remove(0, 2); // ./leelaz -> leelaz
}
}
Engine() = default;
QString getCmdLine(void) const {
return m_binary + " " + m_options + " " + m_network;
}
QString getNetworkFile(void) const {
return QFileInfo(m_network).baseName();
}
QString m_binary;
QString m_options;
QString m_network;
QStringList m_commands;
};
class Game : QProcess {
public:
Game(const Engine& engine);
~Game() = default;
bool gameStart(const VersionTuple& min_version,
const QString &sgf = QString(),
const int moves = 0);
void move();
bool waitForMove() { return waitReady(); }
bool readMove();
bool nextMove();
bool getScore();
bool loadSgf(const QString &fileName);
bool loadSgf(const QString &fileName, const int moves);
bool writeSgf();
bool loadTraining(const QString &fileName);
bool saveTraining();
bool fixSgf(const Engine& whiteEngine, const bool resignation,
const bool isSelfPlay);
bool dumpTraining();
bool dumpDebug();
void gameQuit();
QString getMove() const { return m_moveDone; }
QString getFile() const { return m_fileName; }
bool setMove(const QString& m);
bool checkGameEnd();
int getWinner();
QString getWinnerName() const { return m_winner; }
int getMovesCount() const { return m_moveNum; }
void setMovesCount(int moves);
int getToMove() const { return m_blackToMove ? BLACK : WHITE; }
QString getResult() const { return m_result.trimmed(); }
enum {
BLACK = 0,
WHITE = 1,
};
private:
enum {
NO_LEELAZ = 1,
PROCESS_DIED,
WRONG_GTP,
LAUNCH_FAILURE
};
Engine m_engine;
QString m_winner;
QString m_fileName;
QString m_moveDone;
QString m_result;
bool m_isHandicap;
bool m_resignation;
bool m_blackToMove;
bool m_blackResigned;
int m_passes;
int m_moveNum;
bool sendGtpCommand(QString cmd);
void checkVersion(const VersionTuple &min_version);
bool waitReady();
bool eatNewLine();
void error(int errnum);
void fixSgfPlayer(QString& sgfData, const Engine& whiteEngine);
void fixSgfComment(QString& sgfData, const Engine& whiteEngine,
const bool isSelfPlay);
void fixSgfResult(QString& sgfData, const bool resignation);
};
#endif /* GAME_H */
leela-zero-0.17/autogtp/Job.cpp 0000664 0000000 0000000 00000015776 13451323157 0016425 0 ustar 00root root 0000000 0000000 /*
This file is part of Leela Zero.
Copyright (C) 2017-2018 Marco Calignano
Leela Zero is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Leela Zero is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Leela Zero. If not, see .
*/
#include "Job.h"
#include "Game.h"
#include "Management.h"
#include
#include
#include
#include
Job::Job(QString gpu, Management *parent) :
m_state(RUNNING),
m_gpu(gpu),
m_boss(parent)
{
}
void Job::init(const Order &o) {
QStringList version_list = o.parameters()["leelazVer"].split(".");
if (version_list.size() < 2) {
QTextStream(stdout)
<< "Unexpected Leela Zero version: " << o.parameters()["leelazVer"] << endl;
exit(EXIT_FAILURE);
}
if (version_list.size() < 3) {
version_list.append("0");
}
std::get<0>(m_leelazMinVersion) = version_list[0].toInt();
std::get<1>(m_leelazMinVersion) = version_list[1].toInt();
std::get<2>(m_leelazMinVersion) = version_list[2].toInt();
}
ProductionJob::ProductionJob(QString gpu, Management *parent) :
Job(gpu, parent),
m_engine(Engine(QString(), QString()))
{
}
ValidationJob::ValidationJob(QString gpu, Management *parent) :
Job(gpu, parent),
m_engineFirst(Engine(QString(), QString())),
m_engineSecond(Engine(QString(), QString()))
{
}
WaitJob::WaitJob(QString gpu, Management *parent) :
Job(gpu, parent)
{
}
Result ProductionJob::execute(){
Result res(Result::Error);
Game game(m_engine);
if (!game.gameStart(m_leelazMinVersion, m_sgf, m_moves)) {
return res;
}
if (!m_sgf.isEmpty()) {
QFile::remove(m_sgf + ".sgf");
if (m_restore) {
game.loadTraining(m_sgf);
QFile::remove(m_sgf + ".train");
}
}
do {
game.move();
if (!game.waitForMove()) {
return res;
}
game.readMove();
m_boss->incMoves();
} while (game.nextMove() && m_state.load() == RUNNING);
switch (m_state.load()) {
case RUNNING:
QTextStream(stdout) << "Game has ended." << endl;
if (game.getScore()) {
game.writeSgf();
game.fixSgf(m_engine, false, true);
game.dumpTraining();
if (m_debug) {
game.dumpDebug();
}
}
res.type(Result::File);
res.add("file", game.getFile());
res.add("winner", game.getWinnerName());
res.add("moves", QString::number(game.getMovesCount()));
break;
case STORING:
game.writeSgf();
game.saveTraining();
res.type(Result::StoreSelfPlayed);
res.add("sgf", game.getFile());
res.add("moves", QString::number(game.getMovesCount()));
break;
default:
break;
}
game.gameQuit();
return res;
}
void ProductionJob::init(const Order &o) {
Job::init(o);
m_engine.m_network = "networks/" + o.parameters()["network"] + ".gz";
m_engine.m_options = " " + o.parameters()["options"] + m_gpu + " -g -q -w ";
if (o.parameters().contains("gtpCommands")) {
m_engine.m_commands = o.parameters()["gtpCommands"].split(",");
}
m_debug = o.parameters()["debug"] == "true";
m_sgf = o.parameters()["sgf"];
m_moves = o.parameters()["moves"].toInt();
m_restore = o.type() == Order::RestoreSelfPlayed;
}
Result ValidationJob::execute(){
Result res(Result::Error);
Game first(m_engineFirst);
if (!first.gameStart(m_leelazMinVersion, m_sgf, m_moves)) {
return res;
}
Game second(m_engineSecond);
if (!second.gameStart(m_leelazMinVersion, m_sgf, m_moves)) {
return res;
}
if (!m_sgf.isEmpty()) {
QFile::remove(m_sgf + ".sgf");
}
const QString stringWhite = "white";
const QString stringBlack = "black";
//Start with the side to move set to the opposite of the expected way around
//because the game playing loop swaps the sides at the start of each iteration.
//This avoids having to test which side is to move on every iteration of the loop.
auto gameToMove = &second;
auto colorToMove = &stringWhite;
auto gameOpponent = &first;
auto colorOpponent = &stringBlack;
if (first.getToMove() == Game::WHITE) {
std::swap(gameToMove, gameOpponent);
std::swap(colorToMove, colorOpponent);
}
do {
std::swap(gameToMove, gameOpponent);
std::swap(colorToMove, colorOpponent);
gameToMove->move();
if (!gameToMove->waitForMove()) {
return res;
}
gameToMove->readMove();
m_boss->incMoves();
gameOpponent->setMove("play " + *colorToMove + " " + gameToMove->getMove());
} while (gameToMove->nextMove() && m_state.load() == RUNNING);
switch (m_state.load()) {
case RUNNING:
QTextStream(stdout) << "Game has ended." << endl;
if (first.getScore()) {
res.add("score", first.getResult());
res.add("winner", first.getWinnerName());
first.writeSgf();
first.fixSgf(m_engineSecond,
(res.parameters()["score"] == "B+Resign"),
false);
res.add("file", first.getFile());
}
res.type(Result::Win);
res.add("moves", QString::number(first.getMovesCount()));
break;
case STORING:
first.writeSgf();
res.type(Result::StoreMatch);
res.add("sgf", first.getFile());
res.add("moves", QString::number(first.getMovesCount()));
break;
default:
break;
}
first.gameQuit();
second.gameQuit();
return res;
}
void ValidationJob::init(const Order &o) {
Job::init(o);
m_engineFirst.m_network = "networks/" + o.parameters()["firstNet"] + ".gz";
m_engineFirst.m_options = " " + o.parameters()["options"] + m_gpu + " -g -q -w ";
if (o.parameters().contains("gtpCommands")) {
m_engineFirst.m_commands = o.parameters()["gtpCommands"].split(",");
}
m_engineSecond.m_network = "networks/" + o.parameters()["secondNet"] + ".gz";
m_engineSecond.m_options = " " + o.parameters()["optionsSecond"] + m_gpu + " -g -q -w ";
if (o.parameters().contains("gtpCommandsSecond")) {
m_engineSecond.m_commands = o.parameters()["gtpCommandsSecond"].split(",");
}
m_sgf = o.parameters()["sgf"];
m_moves = o.parameters()["moves"].toInt();
}
Result WaitJob::execute(){
Result res(Result::Waited);
QThread::sleep(m_minutes * 60);
return res;
}
void WaitJob::init(const Order &o) {
Job::init(o);
m_minutes = o.parameters()["minutes"].toInt();
}
leela-zero-0.17/autogtp/Job.h 0000664 0000000 0000000 00000004376 13451323157 0016064 0 ustar 00root root 0000000 0000000 /*
This file is part of Leela Zero.
Copyright (C) 2017-2018 Marco Calignano
Leela Zero is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Leela Zero is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Leela Zero. If not, see .
*/
#ifndef JOB_H
#define JOB_H
#include "Game.h"
#include "Result.h"
#include "Order.h"
#include
#include
#include
class Management;
using VersionTuple = std::tuple;
class Job : public QObject {
Q_OBJECT
public:
enum {
RUNNING = 0,
FINISHING,
STORING
};
enum {
Production = 0,
Validation
};
Job(QString gpu, Management *parent);
~Job() = default;
virtual Result execute() = 0;
virtual void init(const Order &o);
void finish() { m_state.store(FINISHING); }
void store() {
m_state.store(STORING);
}
protected:
QAtomicInt m_state;
QString m_gpu;
int m_moves;
VersionTuple m_leelazMinVersion;
Management *m_boss;
};
class ProductionJob : public Job {
Q_OBJECT
public:
ProductionJob(QString gpu, Management *parent);
~ProductionJob() = default;
void init(const Order &o);
Result execute();
private:
Engine m_engine;
QString m_sgf;
bool m_debug;
bool m_restore;
};
class ValidationJob : public Job {
Q_OBJECT
public:
ValidationJob(QString gpu, Management *parent);
~ValidationJob() = default;
void init(const Order &o);
Result execute();
private:
Engine m_engineFirst;
Engine m_engineSecond;
QString m_sgf;
};
class WaitJob : public Job {
Q_OBJECT
public:
WaitJob(QString gpu, Management *parent);
~WaitJob() = default;
void init(const Order &o);
Result execute();
private:
int m_minutes;
};
#endif // JOB_H
leela-zero-0.17/autogtp/Management.cpp 0000664 0000000 0000000 00000074077 13451323157 0017766 0 ustar 00root root 0000000 0000000 /*
This file is part of Leela Zero.
Copyright (C) 2017-2018 Marco Calignano
Leela Zero is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Leela Zero is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Leela Zero. If not, see .
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "Management.h"
#include "Game.h"
constexpr int RETRY_DELAY_MIN_SEC = 30;
constexpr int RETRY_DELAY_MAX_SEC = 60 * 60; // 1 hour
constexpr int MAX_RETRIES = 3; // Stop retrying after 3 times
const QString server_url = "https://zero.sjeng.org/";
const QString Leelaz_min_version = "0.12";
Management::Management(const int gpus,
const int games,
const QStringList& gpuslist,
const int ver,
const int maxGames,
const bool delNetworks,
const QString& keep,
const QString& debug)
: m_syncMutex(),
m_gamesThreads(gpus * games),
m_games(games),
m_gpus(gpus),
m_gpusList(gpuslist),
m_selfGames(0),
m_matchGames(0),
m_gamesPlayed(0),
m_keepPath(keep),
m_debugPath(debug),
m_version(ver),
m_fallBack(Order::Error),
m_lastMatch(Order::Error),
m_gamesLeft(maxGames),
m_threadsLeft(gpus * games),
m_delNetworks(delNetworks),
m_lockFile(nullptr) {
}
void Management::runTuningProcess(const QString &tuneCmdLine) {
QTextStream(stdout) << tuneCmdLine << endl;
QProcess tuneProcess;
tuneProcess.start(tuneCmdLine);
tuneProcess.waitForStarted(-1);
while (tuneProcess.state() == QProcess::Running) {
tuneProcess.waitForReadyRead(1000);
QByteArray text = tuneProcess.readAllStandardOutput();
int version_start = text.indexOf("Leela Zero ") + 11;
if (version_start > 10) {
int version_end = text.indexOf(" ", version_start);
m_leelaversion = QString(text.mid(version_start, version_end - version_start));
}
QTextStream(stdout) << text;
QTextStream(stdout) << tuneProcess.readAllStandardError();
}
QTextStream(stdout) << "Found Leela Version : " << m_leelaversion << endl;
tuneProcess.waitForFinished(-1);
}
Order Management::getWork(const QFileInfo &file) {
QTextStream(stdout) << "Got previously stored file" <unlock();
delete m_lockFile;
m_lockFile = nullptr;
return o;
}
void Management::giveAssignments() {
sendAllGames();
//Make the OpenCl tuning before starting the threads
QTextStream(stdout) << "Starting tuning process, please wait..." << endl;
Order tuneOrder = getWork(true);
QString tuneCmdLine("./leelaz --batchsize=5 --tune-only -w networks/");
tuneCmdLine.append(tuneOrder.parameters()["network"] + ".gz");
if (m_gpusList.isEmpty()) {
runTuningProcess(tuneCmdLine);
} else {
for (auto i = 0; i < m_gpusList.size(); ++i) {
runTuningProcess(tuneCmdLine + " --gpu=" + m_gpusList.at(i));
}
}
QTextStream(stdout) << "Tuning process finished" << endl;
m_start = std::chrono::high_resolution_clock::now();
QString myGpu;
for (int gpu = 0; gpu < m_gpus; ++gpu) {
for (int game = 0; game < m_games; ++game) {
int thread_index = gpu * m_games + game;
if (m_gpusList.isEmpty()) {
myGpu = "";
} else {
myGpu = m_gpusList.at(gpu);
}
QTextStream(stdout) << "Starting thread " << game + 1 ;
QTextStream(stdout) << " on device " << gpu << endl;
m_gamesThreads[thread_index] = new Worker(thread_index, myGpu, this);
connect(m_gamesThreads[thread_index],
&Worker::resultReady,
this,
&Management::getResult,
Qt::DirectConnection);
QFileInfo finfo = getNextStored();
if (!finfo.fileName().isEmpty()) {
m_gamesThreads[thread_index]->order(getWork(finfo));
} else {
m_gamesThreads[thread_index]->order(getWork());
}
m_gamesThreads[thread_index]->start();
}
}
}
void Management::storeGames() {
for (int i = 0; i < m_gpus * m_games; ++i) {
m_gamesThreads[i]->doStore();
}
wait();
}
void Management::wait() {
QTextStream(stdout) << "Management: waiting for workers" << endl;
for (int i = 0; i < m_gpus * m_games; ++i) {
m_gamesThreads[i]->wait();
QTextStream(stdout) << "Management: Worker " << i+1 << " ended" << endl;
}
}
void Management::getResult(Order ord, Result res, int index, int duration) {
if (res.type() == Result::Error) {
exit(1);
}
m_syncMutex.lock();
m_gamesPlayed++;
switch (res.type()) {
case Result::File:
m_selfGames++,
uploadData(res.parameters(), ord.parameters());
printTimingInfo(duration);
break;
case Result::Win:
case Result::Loss:
m_matchGames++,
uploadResult(res.parameters(), ord.parameters());
printTimingInfo(duration);
break;
}
sendAllGames();
if (m_gamesLeft == 0) {
m_gamesThreads[index]->doFinish();
if (m_threadsLeft > 1) {
--m_threadsLeft;
} else {
sendQuit();
}
} else {
if (m_gamesLeft > 0) --m_gamesLeft;
QFileInfo finfo = getNextStored();
if (!finfo.fileName().isEmpty()) {
m_gamesThreads[index]->order(getWork(finfo));
} else {
m_gamesThreads[index]->order(getWork());
}
}
m_syncMutex.unlock();
}
QFileInfo Management::getNextStored() {
QFileInfo fi;
checkStoredGames();
while (!m_storedFiles.isEmpty()) {
fi = m_storedFiles.takeFirst();
m_lockFile = new QLockFile(fi.fileName()+".lock");
if (m_lockFile->tryLock(10) &&
fi.exists()) {
break;
}
delete m_lockFile;
m_lockFile = nullptr;
}
return fi;
}
void Management::printTimingInfo(float duration) {
auto game_end = std::chrono::high_resolution_clock::now();
auto total_time_s =
std::chrono::duration_cast(game_end - m_start);
auto total_time_min =
std::chrono::duration_cast(total_time_s);
auto total_time_millis =
std::chrono::duration_cast(total_time_s);
QTextStream(stdout)
<< m_gamesPlayed << " game(s) (" << m_selfGames << " self played and "
<< m_matchGames << " matches) played in "
<< total_time_min.count() << " minutes = "
<< total_time_s.count() / m_gamesPlayed << " seconds/game, "
<< total_time_millis.count() / m_movesMade.load() << " ms/move"
<< ", last game took " << int(duration) << " seconds." << endl;
}
QString Management::getOption(const QJsonObject &ob, const QString &key, const QString &opt, const QString &defValue) {
QString res;
if (ob.contains(key)) {
res.append(opt + ob.value(key).toString() + " ");
} else {
if (defValue != "") {
res.append(opt + defValue + " ");
}
}
return res;
}
QString Management::getBoolOption(const QJsonObject &ob, const QString &key, const QString &opt, bool defValue) {
QString res;
if (ob.contains(key)) {
if (ob.value(key).toString().compare("true", Qt::CaseInsensitive) == 0) {
res.append(opt + " ");
}
} else {
if (defValue) {
res.append(opt + " ");
}
}
return res;
}
QString Management::getOptionsString(const QJsonObject &opt, const QString &rnd) {
QString options;
options.append(getOption(opt, "playouts", " -p ", ""));
options.append(getOption(opt, "visits", " -v ", ""));
options.append(getOption(opt, "resignation_percent", " -r ", "1"));
options.append(getOption(opt, "randomcnt", " -m ", "30"));
options.append(getOption(opt, "threads", " -t ", "6"));
options.append(getOption(opt, "batchsize", " --batchsize ", "5"));
options.append(getBoolOption(opt, "dumbpass", " -d ", true));
options.append(getBoolOption(opt, "noise", " -n ", true));
options.append(" --noponder ");
if (rnd != "") {
options.append(" -s " + rnd + " ");
}
return options;
}
QString Management::getGtpCommandsString(const QJsonValue >pCommands) {
const auto gtpCommandsJsonDoc = QJsonDocument(gtpCommands.toArray());
const auto gtpCommandsJson = gtpCommandsJsonDoc.toJson(QJsonDocument::Compact);
auto gtpCommandsString = QVariant(gtpCommandsJson).toString();
gtpCommandsString.remove(QRegularExpression("[\\[\\]\"]"));
return gtpCommandsString;
}
Order Management::getWorkInternal(bool tuning) {
Order o(Order::Error);
/*
{
cmd : "match",
white_hash : "223737476718d58a4a5b0f317a1eeeb4b38f0c06af5ab65cb9d76d68d9abadb6",
black_hash : "92c658d7325fe38f0c8adbbb1444ed17afd891b9f208003c272547a7bcb87909",
options_hash : "c2e3",
minimum_autogtp_version: "16",
random_seed: "2301343010299460478",
minimum_leelaz_version: "0.15",
options : {
playouts : "1000",
visits: "3201",
resignation_percent : "3",
noise : "true",
randomcnt : "30"
},
white_options : {
playouts : "0",
visits: "1601",
resignation_percent : "5",
noise : "false",
randomcnt : "0"
},
white_hash_gzip_hash: "23c29bf777e446b5c3fb0e6e7fa4d53f15b99cc0c25798b70b57877b55bf1638",
black_hash_gzip_hash: "ccfe6023456aaaa423c29bf777e4aab481245289aaaabb70b7b5380992377aa8",
hash_sgf_hash: "7dbccc5ad9eb38f0135ff7ec860f0e81157f47dfc0a8375cef6bf1119859e537",
moves_count: "92",
gtp_commands : [ "time_settings 600 30 1", "komi 0.5", "fixed_handicap 2" ],
white_gtp_commands : [ "time_settings 0 10 1", "komi 0.5", "fixed_handicap 2" ],
}
{
cmd : "selfplay",
hash : "223737476718d58a4a5b0f317a1eeeb4b38f0c06af5ab65cb9d76d68d9abadb6",
options_hash : "ee21",
minimum_autogtp_version: "16",
random_seed: "2301343010299460478",
minimum_leelaz_version: "0.15",
options : {
playouts : "1000",
visits: "3201",
resignation_percent : "3",
noise : "true",
randomcnt : "30"
},
hash_gzip_hash: "23c29bf777e446b5c3fb0e6e7fa4d53f15b99cc0c25798b70b57877b55bf1638",
hash_sgf_hash: "7dbccc5ad9eb38f0135ff7ec860f0e81157f47dfc0a8375cef6bf1119859e537",
moves_count: "92",
gtp_commands : [ "time_settings 600 30 1", "komi 0.5", "fixed_handicap 4" ],
}
{
"cmd" : "wait",
"minutes" : "5",
}
*/
QString prog_cmdline("curl");
#ifdef WIN32
prog_cmdline.append(".exe");
#endif
prog_cmdline.append(" -s -J");
prog_cmdline.append(" "+server_url+"get-task/");
if (tuning) {
prog_cmdline.append("0");
} else {
prog_cmdline.append(QString::number(AUTOGTP_VERSION));
if (!m_leelaversion.isEmpty())
prog_cmdline.append("/"+m_leelaversion);
}
QProcess curl;
curl.start(prog_cmdline);
curl.waitForFinished(-1);
if (curl.exitCode()) {
throw NetworkException("Curl returned non-zero exit code "
+ std::to_string(curl.exitCode()));
return o;
}
QJsonDocument doc;
QJsonParseError parseError;
doc = QJsonDocument::fromJson(curl.readAllStandardOutput(), &parseError);
if (parseError.error != QJsonParseError::NoError) {
std::string errorString = parseError.errorString().toUtf8().constData();
throw NetworkException("JSON parse error: " + errorString);
}
if (!tuning) {
QTextStream(stdout) << doc.toJson() << endl;
}
QMap parameters;
QJsonObject ob = doc.object();
//checking client version
int required_version = 0;
if (ob.contains("required_client_version")) {
required_version = ob.value("required_client_version").toString().toInt();
} else if (ob.contains("minimum_autogtp_version")) {
required_version = ob.value("minimum_autogtp_version").toString().toInt();
}
if (required_version > m_version) {
QTextStream(stdout) << "Required client version: " << required_version << endl;
QTextStream(stdout) << ' ' << endl;
QTextStream(stdout)
<< "Server requires client version " << required_version
<< " but we are version " << m_version << endl;
QTextStream(stdout)
<< "Check https://github.com/gcp/leela-zero for updates." << endl;
exit(EXIT_FAILURE);
}
//passing leela version
QString leelazVersion = Leelaz_min_version;
if (ob.contains("leelaz_version")) {
leelazVersion = ob.value("leelaz_version").toString();
} else if (ob.contains("minimum_leelaz_version")) {
leelazVersion = ob.value("minimum_leelaz_version").toString();
}
parameters["leelazVer"] = leelazVersion;
//getting the random seed
QString rndSeed = "0";
if (ob.contains("random_seed")) {
rndSeed = ob.value("random_seed").toString();
}
parameters["rndSeed"] = rndSeed;
if (rndSeed == "0") {
rndSeed = "";
}
//parsing options
if (ob.contains("options")) {
parameters["optHash"] = ob.value("options_hash").toString();
parameters["options"] = getOptionsString(ob.value("options").toObject(), rndSeed);
}
if (ob.contains("gtp_commands")) {
parameters["gtpCommands"] = getGtpCommandsString(ob.value("gtp_commands"));
}
if (ob.contains("hash_sgf_hash")) {
parameters["sgf"] = fetchGameData(ob.value("hash_sgf_hash").toString(), "sgf");
parameters["moves"] = ob.contains("moves_count") ?
ob.value("moves_count").toString() : "0";
}
parameters["debug"] = !m_debugPath.isEmpty() ? "true" : "false";
if (!tuning) {
QTextStream(stdout) << "Got new job: " << ob.value("cmd").toString() << endl;
}
if (ob.value("cmd").toString() == "selfplay") {
QString net = ob.value("hash").toString();
QString gzipHash = ob.value("hash_gzip_hash").toString();
fetchNetwork(net, gzipHash);
parameters["network"] = net;
o.type(Order::Production);
o.parameters(parameters);
if (m_delNetworks &&
m_fallBack.parameters()["network"] != net) {
QTextStream(stdout) << "Deleting network " << "networks/"
+ m_fallBack.parameters()["network"] + ".gz" << endl;
QFile::remove("networks/" + m_fallBack.parameters()["network"] + ".gz");
}
m_fallBack = o;
QTextStream(stdout) << "net: " << net << "." << endl;
}
if (ob.value("cmd").toString() == "match") {
QString net1 = ob.value("black_hash").toString();
QString gzipHash1 = ob.value("black_hash_gzip_hash").toString();
QString net2 = ob.value("white_hash").toString();
QString gzipHash2 = ob.value("white_hash_gzip_hash").toString();
fetchNetwork(net1, gzipHash1);
fetchNetwork(net2, gzipHash2);
parameters["firstNet"] = net1;
parameters["secondNet"] = net2;
parameters["optionsSecond"] = ob.contains("white_options") ?
getOptionsString(ob.value("white_options").toObject(), rndSeed) :
parameters["options"];
if (ob.contains("gtp_commands")) {
parameters["gtpCommandsSecond"] = ob.contains("white_gtp_commands") ?
getGtpCommandsString(ob.value("white_gtp_commands")) :
parameters["gtpCommands"];
}
o.type(Order::Validation);
o.parameters(parameters);
if (m_delNetworks) {
if (m_lastMatch.parameters()["firstNet"] != net1 &&
m_lastMatch.parameters()["firstNet"] != net2) {
QTextStream(stdout) << "Deleting network " << "networks/"
+ m_lastMatch.parameters()["firstNet"] + ".gz" << endl;
QFile::remove("networks/" + m_lastMatch.parameters()["firstNet"] + ".gz");
}
if (m_lastMatch.parameters()["secondNet"] != net1 &&
m_lastMatch.parameters()["secondNet"] != net2) {
QTextStream(stdout) << "Deleting network " << "networks/"
+ m_lastMatch.parameters()["secondNet"] + ".gz" << endl;
QFile::remove("networks/" + m_lastMatch.parameters()["secondNet"] + ".gz");
}
}
m_lastMatch = o;
QTextStream(stdout) << "first network: " << net1 << "." << endl;
QTextStream(stdout) << "second network " << net2 << "." << endl;
}
if (ob.value("cmd").toString() == "wait") {
parameters["minutes"] = ob.value("minutes").toString();
o.type(Order::Wait);
o.parameters(parameters);
QTextStream(stdout) << "minutes: " << parameters["minutes"] << "." << endl;
}
return o;
}
Order Management::getWork(bool tuning) {
for (auto retries = 0; retries < MAX_RETRIES; retries++) {
try {
return getWorkInternal(tuning);
} catch (const NetworkException &ex) {
QTextStream(stdout)
<< "Network connection to server failed." << endl;
QTextStream(stdout)
<< ex.what() << endl;
auto retry_delay =
std::min(
RETRY_DELAY_MIN_SEC * std::pow(1.5, retries),
RETRY_DELAY_MAX_SEC);
QTextStream(stdout) << "Retrying in " << retry_delay << " s."
<< endl;
QThread::sleep(retry_delay);
}
}
QTextStream(stdout) << "Maximum number of retries exceeded. Falling back to previous network."
<< endl;
if (m_fallBack.type() != Order::Error) {
QMap map = m_fallBack.parameters();
QString seed = QString::number(QUuid::createUuid().toRfc4122().toHex().left(8).toLongLong(Q_NULLPTR, 16));
QString rs = "-s " + seed + " ";
map["rndSeed"] = seed;
QString opt = map["options"];
QRegularExpression re("-s .* ");
opt.replace(re, rs);
map["options"] = opt;
m_fallBack.parameters(map);
return m_fallBack;
}
exit(EXIT_FAILURE);
}
bool Management::networkExists(const QString &name, const QString &gzipHash) {
if (QFileInfo::exists(name)) {
QFile f(name);
if (f.open(QFile::ReadOnly)) {
QCryptographicHash hash(QCryptographicHash::Sha256);
if (!hash.addData(&f)) {
throw NetworkException("Reading network file failed.");
}
QString result = hash.result().toHex();
if (result == gzipHash) {
return true;
}
QTextStream(stdout) << "Downloaded network hash doesn't match, calculated: "
<< result << " it should be: " << gzipHash << endl;
} else {
QTextStream(stdout)
<< "Unable to open network file for reading." << endl;
if (f.remove()) {
return false;
}
throw NetworkException("Unable to delete the network file."
" Check permissions.");
}
}
return false;
}
void Management::fetchNetwork(const QString &net, const QString &hash) {
QString name = "networks/" + net + ".gz";
if (networkExists(name, hash)) {
return;
}
if (QFileInfo::exists(name)) {
QFile f_gz(name);
// Curl refuses to overwrite, so make sure to delete the gzipped
// network if it exists
f_gz.remove();
}
QString prog_cmdline("curl");
#ifdef WIN32
prog_cmdline.append(".exe");
#endif
// Be quiet, but output the real file name we saved.
// Use the filename from the server.
prog_cmdline.append(" -s -J -o " + name + " ");
prog_cmdline.append(" -w %{filename_effective}");
prog_cmdline.append(" "+server_url + name);
QProcess curl;
curl.start(prog_cmdline);
curl.waitForFinished(-1);
if (curl.exitCode()) {
throw NetworkException("Curl returned non-zero exit code "
+ std::to_string(curl.exitCode()));
}
QByteArray output = curl.readAllStandardOutput();
QString outstr(output);
QStringList outlst = outstr.split("\n");
QString outfile = outlst[0];
QTextStream(stdout) << "Net filename: " << outfile << endl;
return;
}
QString Management::fetchGameData(const QString &name, const QString &extension) {
QString prog_cmdline("curl");
#ifdef WIN32
prog_cmdline.append(".exe");
#endif
const auto fileName = QUuid::createUuid().toRfc4122().toHex();
// Be quiet, but output the real file name we saved.
// Use the filename from the server.
prog_cmdline.append(" -s -J -o " + fileName + "." + extension);
prog_cmdline.append(" -w %{filename_effective}");
prog_cmdline.append(" "+server_url + "view/" + name + "." + extension);
QProcess curl;
curl.start(prog_cmdline);
curl.waitForFinished(-1);
if (curl.exitCode()) {
throw NetworkException("Curl returned non-zero exit code "
+ std::to_string(curl.exitCode()));
}
return fileName;
}
void Management::archiveFiles(const QString &fileName) {
if (!m_keepPath.isEmpty()) {
QFile(fileName + ".sgf").copy(m_keepPath + '/' + fileName + ".sgf");
}
if (!m_debugPath.isEmpty()) {
QFile d(fileName + ".txt.0.gz");
if (d.exists()) {
d.copy(m_debugPath + '/' + fileName + ".txt.0.gz");
}
QFile db(fileName + ".debug.txt.0.gz");
if (db.exists()) {
db.copy(m_debugPath + '/' + fileName + ".debug.txt.0.gz");
}
}
}
void Management::cleanupFiles(const QString &fileName) {
QDir dir;
QStringList filters;
filters << fileName + ".*";
dir.setNameFilters(filters);
dir.setFilter(QDir::Files | QDir::NoSymLinks);
QFileInfoList list = dir.entryInfoList();
for (int i = 0; i < list.size(); ++i) {
QFile(list.at(i).fileName()).remove();
}
}
void Management::gzipFile(const QString &fileName) {
QString gzipCmd ="gzip";
#ifdef WIN32
gzipCmd.append(".exe");
#endif
gzipCmd.append(" " + fileName);
QProcess::execute(gzipCmd);
}
void Management::saveCurlCmdLine(const QStringList &prog_cmdline, const QString &name) {
QString fileName = "curl_save" + QUuid::createUuid().toRfc4122().toHex() + ".bin";
QLockFile lf(fileName + ".lock");
lf.lock();
QFile f(fileName);
if (!f.open(QIODevice::WriteOnly | QIODevice::Text)) {
return;
}
QTextStream out(&f);
out << name << endl;
out << prog_cmdline.size() << endl;
QStringList::ConstIterator it = prog_cmdline.constBegin();
while (it != prog_cmdline.constEnd()) {
out << *it << " " << endl;
++it;
}
f.close();
}
void Management::sendAllGames() {
QDir dir;
QStringList filters;
filters << "curl_save*.bin";
dir.setNameFilters(filters);
dir.setFilter(QDir::Files | QDir::NoSymLinks);
QFileInfoList list = dir.entryInfoList();
for (int i = 0; i < list.size(); ++i) {
QFileInfo fileInfo = list.at(i);
QLockFile lf(fileInfo.fileName()+".lock");
if (!lf.tryLock(10)) {
continue;
}
QFile file(fileInfo.fileName());
if (!file.open(QFile::ReadOnly)) {
continue;
}
QTextStream in(&file);
QString name;
QString tmp;
QStringList lines;
int count;
in >> name;
in >> count;
count = 2 * count - 1;
for (int i = 0; i < count; i++) {
in >> tmp;
lines << tmp;
}
file.close();
bool sent = false;
try {
sent = sendCurl(lines);
if (sent) {
QTextStream(stdout) << "File: " << file.fileName() << " sent" << endl;
file.remove();
cleanupFiles(name);
if (i+1 < list.size()) {
QThread::sleep(10);
}
}
} catch (const NetworkException &ex) {
QTextStream(stdout)
<< "Network connection to server failed." << endl;
QTextStream(stdout)
<< ex.what() << endl;
QTextStream(stdout)
<< "Retrying when next game is finished."
<< endl;
}
}
}
bool Management::sendCurl(const QStringList &lines) {
QString prog_cmdline("curl");
#ifdef WIN32
prog_cmdline.append(".exe");
#endif
QStringList::ConstIterator it = lines.constBegin();
while (it != lines.constEnd()) {
prog_cmdline.append(" " + *it);
++it;
}
QProcess curl;
curl.start(prog_cmdline);
curl.waitForFinished(-1);
if (curl.exitCode()) {
QTextStream(stdout) << "Upload failed. Curl Exit code: "
<< curl.exitCode() << endl;
QTextStream(stdout) << curl.readAllStandardOutput();
throw NetworkException("Curl returned non-zero exit code "
+ std::to_string(curl.exitCode()));
return false;
}
QTextStream(stdout) << curl.readAllStandardOutput();
return (curl.exitCode() == 0);
}
/*
-F winnerhash=223737476718d58a4a5b0f317a1eeeb4b38f0c06af5ab65cb9d76d68d9abadb6
-F loserhash=92c658d7325fe38f0c8adbbb1444ed17afd891b9f208003c272547a7bcb87909
-F clientversion=6
-F winnercolor=black
-F movescount=321
-F score=B+45
-F options_hash=c2e3
-F random_seed=0
-F sgf=@file
https://zero.sjeng.org/submit-match
*/
void Management::uploadResult(const QMap &r, const QMap &l) {
QTextStream(stdout) << "Uploading match: " << r["file"] << ".sgf for networks ";
QTextStream(stdout) << l["firstNet"] << " and " << l["secondNet"] << endl;
archiveFiles(r["file"]);
gzipFile(r["file"] + ".sgf");
QStringList prog_cmdline;
if (r["winner"] == "black") {
prog_cmdline.append("-F winnerhash=" + l["firstNet"]);
prog_cmdline.append("-F loserhash=" + l["secondNet"]);
} else {
prog_cmdline.append("-F winnerhash=" + l["secondNet"]);
prog_cmdline.append("-F loserhash=" + l["firstNet"]);
}
prog_cmdline.append("-F clientversion=" + QString::number(m_version));
prog_cmdline.append("-F winnercolor="+ r["winner"]);
prog_cmdline.append("-F movescount="+ r["moves"]);
prog_cmdline.append("-F score="+ r["score"]);
prog_cmdline.append("-F options_hash="+ l["optHash"]);
prog_cmdline.append("-F random_seed="+ l["rndSeed"]);
prog_cmdline.append("-F sgf=@"+ r["file"] + ".sgf.gz");
prog_cmdline.append(server_url+"submit-match");
bool sent = false;
for (auto retries = 0; retries < MAX_RETRIES; retries++) {
try {
sent = sendCurl(prog_cmdline);
break;
} catch (const NetworkException &ex) {
QTextStream(stdout)
<< "Network connection to server failed." << endl;
QTextStream(stdout)
<< ex.what() << endl;
auto retry_delay =
std::min(
RETRY_DELAY_MIN_SEC * std::pow(1.5, retries),
RETRY_DELAY_MAX_SEC);
QTextStream(stdout) << "Retrying in " << retry_delay << " s."
<< endl;
QThread::sleep(retry_delay);
}
}
if (!sent) {
saveCurlCmdLine(prog_cmdline, r["file"]);
return;
}
cleanupFiles(r["file"]);
}
/*
-F networkhash=223737476718d58a4a5b0f317a1eeeb4b38f0c06af5ab65cb9d76d68d9abadb6
-F clientversion=6
-F options_hash=ee21
-F random_seed=1
-F sgf=@file
-F trainingdata=@data_file
https://zero.sjeng.org/submit
*/
void Management::uploadData(const QMap &r, const QMap &l) {
QTextStream(stdout) << "Uploading game: " << r["file"] << ".sgf for network " << l["network"] << endl;
archiveFiles(r["file"]);
gzipFile(r["file"] + ".sgf");
QStringList prog_cmdline;
prog_cmdline.append("-F networkhash=" + l["network"]);
prog_cmdline.append("-F clientversion=" + QString::number(m_version));
prog_cmdline.append("-F options_hash="+ l["optHash"]);
prog_cmdline.append("-F movescount="+ r["moves"]);
prog_cmdline.append("-F winnercolor="+ r["winner"]);
prog_cmdline.append("-F random_seed="+ l["rndSeed"]);
prog_cmdline.append("-F sgf=@" + r["file"] + ".sgf.gz");
prog_cmdline.append("-F trainingdata=@" + r["file"] + ".txt.0.gz");
prog_cmdline.append(server_url+"submit");
bool sent = false;
for (auto retries = 0; retries < MAX_RETRIES; retries++) {
try {
sent = sendCurl(prog_cmdline);
break;
} catch (const NetworkException &ex) {
QTextStream(stdout)
<< "Network connection to server failed." << endl;
QTextStream(stdout)
<< ex.what() << endl;
auto retry_delay =
std::min(
RETRY_DELAY_MIN_SEC * std::pow(1.5, retries),
RETRY_DELAY_MAX_SEC);
QTextStream(stdout) << "Retrying in " << retry_delay << " s."
<< endl;
QThread::sleep(retry_delay);
}
}
if (!sent) {
saveCurlCmdLine(prog_cmdline, r["file"]);
return;
}
cleanupFiles(r["file"]);
}
void Management::checkStoredGames() {
QDir dir;
QStringList filters;
filters << "storefile*.bin";
dir.setNameFilters(filters);
dir.setFilter(QDir::Files | QDir::NoSymLinks);
m_storedFiles = dir.entryInfoList();
}
leela-zero-0.17/autogtp/Management.h 0000664 0000000 0000000 00000007211 13451323157 0017415 0 ustar 00root root 0000000 0000000 /*
This file is part of Leela Zero.
Copyright (C) 2017-2018 Marco Calignano
Leela Zero is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Leela Zero is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Leela Zero. If not, see .
*/
#ifndef MANAGEMENT_H
#define MANAGEMENT_H
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "Worker.h"
constexpr int AUTOGTP_VERSION = 18;
class Management : public QObject {
Q_OBJECT
public:
Management(const int gpus,
const int games,
const QStringList& gpuslist,
const int ver,
const int maxGame,
const bool delNetworks,
const QString& keep,
const QString& debug);
~Management() = default;
void giveAssignments();
void incMoves() { m_movesMade++; }
void wait();
signals:
void sendQuit();
public slots:
void getResult(Order ord, Result res, int index, int duration);
void storeGames();
private:
struct NetworkException: public std::runtime_error
{
NetworkException(std::string const& message)
: std::runtime_error("NetworkException: " + message)
{}
};
QMutex m_syncMutex;
QVector m_gamesThreads;
int m_games;
int m_gpus;
QStringList m_gpusList;
int m_selfGames;
int m_matchGames;
int m_gamesPlayed;
QAtomicInt m_movesMade;
QString m_keepPath;
QString m_debugPath;
int m_version;
std::chrono::high_resolution_clock::time_point m_start;
int m_storeGames;
QList m_storedFiles;
Order m_fallBack;
Order m_lastMatch;
int m_gamesLeft;
int m_threadsLeft;
bool m_delNetworks;
QLockFile *m_lockFile;
QString m_leelaversion;
Order getWorkInternal(bool tuning);
Order getWork(bool tuning = false);
Order getWork(const QFileInfo &file);
QString getOption(const QJsonObject &ob, const QString &key, const QString &opt, const QString &defValue);
QString getBoolOption(const QJsonObject &ob, const QString &key, const QString &opt, bool defValue);
QString getOptionsString(const QJsonObject &opt, const QString &rnd);
QString getGtpCommandsString(const QJsonValue >pCommands);
void sendAllGames();
void checkStoredGames();
QFileInfo getNextStored();
bool networkExists(const QString &name, const QString &gzipHash);
void fetchNetwork(const QString &net, const QString &hash);
QString fetchGameData(const QString &name, const QString &extension);
void printTimingInfo(float duration);
void runTuningProcess(const QString &tuneCmdLine);
void gzipFile(const QString &fileName);
bool sendCurl(const QStringList &lines);
void saveCurlCmdLine(const QStringList &prog_cmdline, const QString &name);
void archiveFiles(const QString &fileName);
void cleanupFiles(const QString &fileName);
void uploadData(const QMap &r, const QMap &l);
void uploadResult(const QMap &r, const QMap &l);
};
#endif
leela-zero-0.17/autogtp/Order.cpp 0000664 0000000 0000000 00000003224 13451323157 0016747 0 ustar 00root root 0000000 0000000 /*
This file is part of Leela Zero.
Copyright (C) 2017-2018 Marco Calignano
Leela Zero is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Leela Zero is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Leela Zero. If not, see .
*/
#include "Order.h"
#include
#include
void Order::save(const QString &file) {
QFile f(file);
if (!f.open(QIODevice::WriteOnly | QIODevice::Text)) {
return;
}
QTextStream out(&f);
out << m_type << endl;
out << m_parameters.size() << endl;
for (QString key : m_parameters.keys())
{
out << key << " " << m_parameters.value(key) << endl;
}
out.flush();
f.close();
}
void Order::load(const QString &file) {
QFile f(file);
if (!f.open(QIODevice::ReadOnly | QIODevice::Text)) {
return;
}
QTextStream in(&f);
in >> m_type;
int count;
in >> count;
QString key;
for (int i = 0; i < count; i++) {
in >> key;
if (key.contains("options") || key.contains("gtpCommands")) {
m_parameters[key] = in.readLine().remove(0, 1);
} else {
in >> m_parameters[key];
}
}
f.close();
}
leela-zero-0.17/autogtp/Order.h 0000664 0000000 0000000 00000003465 13451323157 0016423 0 ustar 00root root 0000000 0000000 /*
This file is part of Leela Zero.
Copyright (C) 2017-2018 Marco Calignano
Leela Zero is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Leela Zero is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Leela Zero. If not, see .
*/
#ifndef ORDER_H
#define ORDER_H
#include
#include
class Order {
public:
enum {
Error = 0,
Production,
Validation,
Wait,
RestoreMatch,
RestoreSelfPlayed
};
Order() = default;
Order(int t, QMap p = QMap()) { m_type = t; m_parameters = p; }
Order(const Order &o) { m_type = o.m_type; m_parameters = o.m_parameters; }
Order &operator=(const Order &o) { m_type = o.m_type; m_parameters = o.m_parameters; return *this; }
~Order() = default;
void type(int t) { m_type = t; }
int type() const { return m_type; }
QMap parameters() const { return m_parameters; }
void parameters(const QMap &l) { m_parameters = l; }
void add(const QString &key, const QString &value) { m_parameters[key] = value; }
bool isValid() { return (m_type > Error && m_type <= RestoreSelfPlayed); }
void save(const QString &file);
void load(const QString &file);
private:
int m_type;
QMap m_parameters;
};
#endif // ORDER_H
leela-zero-0.17/autogtp/README.md 0000664 0000000 0000000 00000002227 13451323157 0016451 0 ustar 00root root 0000000 0000000 # autogtp
This is a self-play tool for Leela-Zero. When launched, it will fetch the
best network from the server so far, play a game against itself, and upload
the SGF and training data at the end of the game.
# Requirements
* Qt 5.3 or later with qmake
* C++14 capable compiler
* curl
* gzip and gunzip
## Example of compiling - Ubuntu
sudo apt install qt5-default qt5-qmake curl
qmake -qt5
make
## Compiling under Visual Studio - Windows
You have to download and install Qt and Qt VS Tools. You only need QtCore to
run. Locate a copy of curl.exe and gzip.exe (a previous Leela release package
will contain them) and put them into the msvc subdir.
Loading leela-zero2015.sln or leela-zero2017.sln will then load this project
and should compile. The two exes (curl.exe and gzip.exe) will also be copied to
the output folder after the build, making it possible to run autogtp.exe
directly.
# Running
Copy the compiled leelaz binary into the autogtp directory, and run
autogtp.
cp ../build/leelaz .
./autogtp
While autogtp is running, typing q+Enter will save the processed data and exit. When autogtp runs next, autogtp will continue the game.
leela-zero-0.17/autogtp/Result.h 0000664 0000000 0000000 00000002706 13451323157 0016623 0 ustar 00root root 0000000 0000000 /*
This file is part of Leela Zero.
Copyright (C) 2017-2018 Marco Calignano
Leela Zero is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Leela Zero is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Leela Zero. If not, see .
*/
#ifndef RESULT_H
#define RESULT_H
#include
#include
class Result {
public:
enum Type {
File = 0,
Win,
Loss,
Waited,
StoreMatch,
StoreSelfPlayed,
Error
};
Result() = default;
Result(int t, QMap n = QMap()) { m_type = t, m_parameters = n; }
~Result() = default;
void type(int t) { m_type = t; }
int type() { return m_type; }
void add(const QString &name, const QString &value) { m_parameters[name] = value; }
QMap parameters() { return m_parameters; }
void clear() { m_parameters.clear(); }
private:
int m_type;
QMap m_parameters;
};
#endif // RESULT_H
leela-zero-0.17/autogtp/Worker.cpp 0000664 0000000 0000000 00000005745 13451323157 0017157 0 ustar 00root root 0000000 0000000 /*
This file is part of Leela Zero.
Copyright (C) 2017-2018 Marco Calignano
Leela Zero is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Leela Zero is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Leela Zero. If not, see .
*/
#include "Worker.h"
#include "Game.h"
#include
#include
#include
#include
Worker::Worker(int index, const QString& gpuIndex, Management *parent) :
m_index(index),
m_state(),
m_gpu(""),
m_job(nullptr),
m_boss(parent)
{
if (!gpuIndex.isEmpty()) {
m_gpu = " --gpu=" + gpuIndex + " ";
}
}
void Worker::doStore() {
QTextStream(stdout) << "Storing current game ..." << endl;
m_job->store();
m_state.store(STORING);
}
void Worker::order(Order o)
{
if (!o.isValid()) {
if (m_job != nullptr) {
m_job->finish();
}
return;
}
if (m_todo.type() != o.type() || m_job == nullptr) {
createJob(o.type());
}
m_todo = o;
m_job->init(m_todo);
}
void Worker::createJob(int type) {
if (m_job != nullptr) {
delete m_job;
}
switch (type) {
case Order::Production:
case Order::RestoreSelfPlayed:
m_job = new ProductionJob(m_gpu, m_boss);
break;
case Order::Validation:
case Order::RestoreMatch:
m_job = new ValidationJob(m_gpu, m_boss);
break;
case Order::Wait:
m_job = new WaitJob(m_gpu, m_boss);
break;
}
}
void Worker::run() {
Result res;
do {
auto start = std::chrono::high_resolution_clock::now();
res = m_job->execute();
auto end = std::chrono::high_resolution_clock::now();
auto gameDuration =
std::chrono::duration_cast(end - start).count();
if (m_state != STORING) {
emit resultReady(m_todo, res, m_index, gameDuration);
}
} while (m_state == RUNNING);
if (m_state == STORING) {
m_todo.add("moves", res.parameters()["moves"]);
m_todo.add("sgf", res.parameters()["sgf"]);
if (res.type() == Result::StoreMatch) {
m_todo.type(Order::RestoreMatch);
} else {
m_todo.type(Order::RestoreSelfPlayed);
}
QString unique = QUuid::createUuid().toRfc4122().toHex();
QLockFile fi("storefile" + unique + ".bin.lock");
fi.lock();
m_todo.save("storefile" + unique + ".bin");
fi.unlock();
}
QTextStream(stdout) << "Program ends: quitting current worker." << endl;
}
leela-zero-0.17/autogtp/Worker.h 0000664 0000000 0000000 00000002704 13451323157 0016614 0 ustar 00root root 0000000 0000000 /*
This file is part of Leela Zero.
Copyright (C) 2017-2018 Marco Calignano
Leela Zero is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Leela Zero is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Leela Zero. If not, see .
*/
#ifndef WORKER_H
#define WORKER_H
#include "Job.h"
#include "Order.h"
#include
#include
class Management;
class Worker : public QThread {
Q_OBJECT
public:
enum {
RUNNING = 0,
FINISHING,
STORING
};
Worker(int index, const QString& gpuIndex, Management *parent);
~Worker() = default;
void order(Order o);
void doFinish() { m_job->finish(); m_state.store(FINISHING); }
void doStore();
void run() override;
signals:
void resultReady(Order o, Result r, int index, int duration);
private:
int m_index;
QAtomicInt m_state;
QString m_gpu;
Order m_todo;
Job *m_job;
Management *m_boss;
void createJob(int type);
};
#endif // WORKER_H
leela-zero-0.17/autogtp/autogtp.pro 0000664 0000000 0000000 00000001337 13451323157 0017400 0 ustar 00root root 0000000 0000000 QT_REQ_MAJOR_VERSION = 5
QT_REQ_MINOR_VERSION = 3
QT_REQ_VERSION = "$$QT_REQ_MAJOR_VERSION"."$$QT_REQ_MINOR_VERSION"
lessThan(QT_MAJOR_VERSION, $$QT_REQ_MAJOR_VERSION) {
error(Minimum supported Qt version is $$QT_REQ_VERSION!)
}
equals(QT_MAJOR_VERSION, $$QT_REQ_MAJOR_VERSION):lessThan(QT_MINOR_VERSION, $$QT_REQ_MINOR_VERSION) {
error(Minimum supported Qt version is $$QT_REQ_VERSION!)
}
TARGET = autogtp
CONFIG += c++14
CONFIG += warn_on
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
SOURCES += main.cpp \
Game.cpp \
Worker.cpp \
Order.cpp \
Job.cpp \
Management.cpp
HEADERS += \
Game.h \
Worker.h \
Job.h \
Order.h \
Result.h \
Management.h \
Console.h
leela-zero-0.17/autogtp/main.cpp 0000664 0000000 0000000 00000013154 13451323157 0016623 0 ustar 00root root 0000000 0000000 /*
This file is part of Leela Zero.
Copyright (C) 2017-2018 Gian-Carlo Pascutto
Copyright (C) 2017-2018 Marco Calignano
Leela Zero is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Leela Zero is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Leela Zero. If not, see .
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#ifdef WIN32
#include
#endif
#include
#include
#include "Game.h"
#include "Management.h"
#include "Console.h"
int main(int argc, char *argv[]) {
QCoreApplication app(argc, argv);
app.setApplicationName("autogtp");
app.setApplicationVersion(QString("v%1").arg(AUTOGTP_VERSION));
QCommandLineParser parser;
parser.addHelpOption();
parser.addVersionOption();
QCommandLineOption gamesNumOption(
{"g", "gamesNum"},
"Play 'gamesNum' games on one device (GPU/CPU) at the same time.",
"num", "1");
QCommandLineOption gpusOption(
{"u", "gpus"},
"Index of the device(s) to use for multiple devices support.",
"num");
QCommandLineOption keepSgfOption(
{"k", "keepSgf" },
"Save SGF files after each self-play game.",
"output directory");
QCommandLineOption keepDebugOption(
{ "d", "debug" }, "Save training and extra debug files after each self-play game.",
"output directory");
QCommandLineOption timeoutOption(
{ "t", "timeout" }, "Save running games after the timeout (in minutes) is passed and then exit.",
"time in minutes");
QCommandLineOption singleOption(
{ "s", "single" }, "Exit after the first game is completed.",
"");
QCommandLineOption maxOption(
{ "m", "maxgames" }, "Exit after the given number of games is completed.",
"max number of games");
QCommandLineOption eraseOption(
{ "e", "erase" }, "Erase old networks when new ones are available.",
"");
parser.addOption(gamesNumOption);
parser.addOption(gpusOption);
parser.addOption(keepSgfOption);
parser.addOption(keepDebugOption);
parser.addOption(timeoutOption);
parser.addOption(singleOption);
parser.addOption(maxOption);
parser.addOption(eraseOption);
// Process the actual command line arguments given by the user
parser.process(app);
int gamesNum = parser.value(gamesNumOption).toInt();
QStringList gpusList = parser.values(gpusOption);
int gpusNum = gpusList.count();
if (gpusNum == 0) {
gpusNum = 1;
}
int maxNum = -1;
if (parser.isSet(maxOption)) {
maxNum = parser.value(maxOption).toInt();
if (maxNum == 0) {
maxNum = 1;
}
if (maxNum < gpusNum * gamesNum) {
gamesNum = maxNum / gpusNum;
if (gamesNum == 0) {
gamesNum = 1;
gpusNum = 1;
}
}
maxNum -= (gpusNum * gamesNum);
}
if (parser.isSet(singleOption)) {
gamesNum = 1;
gpusNum = 1;
maxNum = 0;
}
// Map streams
QTextStream cerr(stderr, QIODevice::WriteOnly);
cerr << "AutoGTP v" << AUTOGTP_VERSION << endl;
cerr << "Using " << gamesNum << " game thread(s) per device." << endl;
if (parser.isSet(keepSgfOption)) {
if (!QDir().mkpath(parser.value(keepSgfOption))) {
cerr << "Couldn't create output directory for self-play SGF files!"
<< endl;
return EXIT_FAILURE;
}
}
if (parser.isSet(keepDebugOption)) {
if (!QDir().mkpath(parser.value(keepDebugOption))) {
cerr << "Couldn't create output directory for self-play Debug files!"
<< endl;
return EXIT_FAILURE;
}
}
Console *cons = nullptr;
if (!QDir().mkpath("networks")) {
cerr << "Couldn't create the directory for the networks files!"
<< endl;
return EXIT_FAILURE;
}
Management *boss = new Management(gpusNum, gamesNum, gpusList, AUTOGTP_VERSION, maxNum,
parser.isSet(eraseOption), parser.value(keepSgfOption),
parser.value(keepDebugOption));
QObject::connect(&app, &QCoreApplication::aboutToQuit, boss, &Management::storeGames);
QTimer *timer = new QTimer();
boss->giveAssignments();
if (parser.isSet(timeoutOption)) {
QObject::connect(timer, &QTimer::timeout, &app, &QCoreApplication::quit);
timer->start(parser.value(timeoutOption).toInt() * 60000);
}
if (parser.isSet(singleOption) || parser.isSet(maxOption)) {
QObject::connect(boss, &Management::sendQuit, &app, &QCoreApplication::quit);
}
if (true) {
cons = new Console();
QObject::connect(cons, &Console::sendQuit, &app, &QCoreApplication::quit);
}
return app.exec();
}
leela-zero-0.17/cmake/ 0000775 0000000 0000000 00000000000 13451323157 0014564 5 ustar 00root root 0000000 0000000 leela-zero-0.17/cmake/Modules/ 0000775 0000000 0000000 00000000000 13451323157 0016174 5 ustar 00root root 0000000 0000000 leela-zero-0.17/cmake/Modules/CMakePushCheckState.cmake 0000664 0000000 0000000 00000006660 13451323157 0022765 0 ustar 00root root 0000000 0000000 # Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.
#.rst:
# CMakePushCheckState
# -------------------
#
#
#
# This module defines three macros: CMAKE_PUSH_CHECK_STATE()
# CMAKE_POP_CHECK_STATE() and CMAKE_RESET_CHECK_STATE() These macros can
# be used to save, restore and reset (i.e., clear contents) the state of
# the variables CMAKE_REQUIRED_FLAGS, CMAKE_REQUIRED_DEFINITIONS,
# CMAKE_REQUIRED_LIBRARIES, CMAKE_REQUIRED_INCLUDES and CMAKE_EXTRA_INCLUDE_FILES
# used by the various Check-files coming with CMake, like e.g.
# check_function_exists() etc. The variable contents are pushed on a
# stack, pushing multiple times is supported. This is useful e.g. when
# executing such tests in a Find-module, where they have to be set, but
# after the Find-module has been executed they should have the same
# value as they had before.
#
# CMAKE_PUSH_CHECK_STATE() macro receives optional argument RESET.
# Whether it's specified, CMAKE_PUSH_CHECK_STATE() will set all
# CMAKE_REQUIRED_* variables to empty values, same as
# CMAKE_RESET_CHECK_STATE() call will do.
#
# Usage:
#
# ::
#
# cmake_push_check_state(RESET)
# set(CMAKE_REQUIRED_DEFINITIONS -DSOME_MORE_DEF)
# check_function_exists(...)
# cmake_reset_check_state()
# set(CMAKE_REQUIRED_DEFINITIONS -DANOTHER_DEF)
# check_function_exists(...)
# cmake_pop_check_state()
macro(CMAKE_RESET_CHECK_STATE)
set(CMAKE_EXTRA_INCLUDE_FILES)
set(CMAKE_REQUIRED_INCLUDES)
set(CMAKE_REQUIRED_DEFINITIONS)
set(CMAKE_REQUIRED_LIBRARIES)
set(CMAKE_REQUIRED_FLAGS)
set(CMAKE_REQUIRED_QUIET)
endmacro()
macro(CMAKE_PUSH_CHECK_STATE)
if(NOT DEFINED _CMAKE_PUSH_CHECK_STATE_COUNTER)
set(_CMAKE_PUSH_CHECK_STATE_COUNTER 0)
endif()
math(EXPR _CMAKE_PUSH_CHECK_STATE_COUNTER "${_CMAKE_PUSH_CHECK_STATE_COUNTER}+1")
set(_CMAKE_EXTRA_INCLUDE_FILES_SAVE_${_CMAKE_PUSH_CHECK_STATE_COUNTER} ${CMAKE_EXTRA_INCLUDE_FILES})
set(_CMAKE_REQUIRED_INCLUDES_SAVE_${_CMAKE_PUSH_CHECK_STATE_COUNTER} ${CMAKE_REQUIRED_INCLUDES})
set(_CMAKE_REQUIRED_DEFINITIONS_SAVE_${_CMAKE_PUSH_CHECK_STATE_COUNTER} ${CMAKE_REQUIRED_DEFINITIONS})
set(_CMAKE_REQUIRED_LIBRARIES_SAVE_${_CMAKE_PUSH_CHECK_STATE_COUNTER} ${CMAKE_REQUIRED_LIBRARIES})
set(_CMAKE_REQUIRED_FLAGS_SAVE_${_CMAKE_PUSH_CHECK_STATE_COUNTER} ${CMAKE_REQUIRED_FLAGS})
set(_CMAKE_REQUIRED_QUIET_SAVE_${_CMAKE_PUSH_CHECK_STATE_COUNTER} ${CMAKE_REQUIRED_QUIET})
if (${ARGC} GREATER 0 AND "${ARGV0}" STREQUAL "RESET")
cmake_reset_check_state()
endif()
endmacro()
macro(CMAKE_POP_CHECK_STATE)
# don't pop more than we pushed
if("${_CMAKE_PUSH_CHECK_STATE_COUNTER}" GREATER "0")
set(CMAKE_EXTRA_INCLUDE_FILES ${_CMAKE_EXTRA_INCLUDE_FILES_SAVE_${_CMAKE_PUSH_CHECK_STATE_COUNTER}})
set(CMAKE_REQUIRED_INCLUDES ${_CMAKE_REQUIRED_INCLUDES_SAVE_${_CMAKE_PUSH_CHECK_STATE_COUNTER}})
set(CMAKE_REQUIRED_DEFINITIONS ${_CMAKE_REQUIRED_DEFINITIONS_SAVE_${_CMAKE_PUSH_CHECK_STATE_COUNTER}})
set(CMAKE_REQUIRED_LIBRARIES ${_CMAKE_REQUIRED_LIBRARIES_SAVE_${_CMAKE_PUSH_CHECK_STATE_COUNTER}})
set(CMAKE_REQUIRED_FLAGS ${_CMAKE_REQUIRED_FLAGS_SAVE_${_CMAKE_PUSH_CHECK_STATE_COUNTER}})
set(CMAKE_REQUIRED_QUIET ${_CMAKE_REQUIRED_QUIET_SAVE_${_CMAKE_PUSH_CHECK_STATE_COUNTER}})
math(EXPR _CMAKE_PUSH_CHECK_STATE_COUNTER "${_CMAKE_PUSH_CHECK_STATE_COUNTER}-1")
endif()
endmacro()
leela-zero-0.17/cmake/Modules/CheckFortranFunctionExists.cmake 0000664 0000000 0000000 00000004216 13451323157 0024460 0 ustar 00root root 0000000 0000000 # Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.
#.rst:
# CheckFortranFunctionExists
# --------------------------
#
# macro which checks if the Fortran function exists
#
# CHECK_FORTRAN_FUNCTION_EXISTS(FUNCTION VARIABLE)
#
# ::
#
# FUNCTION - the name of the Fortran function
# VARIABLE - variable to store the result
# Will be created as an internal cache variable.
#
#
#
# The following variables may be set before calling this macro to modify
# the way the check is run:
#
# ::
#
# CMAKE_REQUIRED_LIBRARIES = list of libraries to link
macro(CHECK_FORTRAN_FUNCTION_EXISTS FUNCTION VARIABLE)
if(NOT DEFINED ${VARIABLE})
message(STATUS "Looking for Fortran ${FUNCTION}")
if(CMAKE_REQUIRED_LIBRARIES)
set(CHECK_FUNCTION_EXISTS_ADD_LIBRARIES
LINK_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES})
else()
set(CHECK_FUNCTION_EXISTS_ADD_LIBRARIES)
endif()
file(WRITE
${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/testFortranCompiler.f
"
program TESTFortran
external ${FUNCTION}
call ${FUNCTION}()
end program TESTFortran
"
)
try_compile(${VARIABLE}
${CMAKE_BINARY_DIR}
${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/testFortranCompiler.f
${CHECK_FUNCTION_EXISTS_ADD_LIBRARIES}
OUTPUT_VARIABLE OUTPUT
)
# message(STATUS "${OUTPUT}")
if(${VARIABLE})
set(${VARIABLE} 1 CACHE INTERNAL "Have Fortran function ${FUNCTION}")
message(STATUS "Looking for Fortran ${FUNCTION} - found")
file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log
"Determining if the Fortran ${FUNCTION} exists passed with the following output:\n"
"${OUTPUT}\n\n")
else()
message(STATUS "Looking for Fortran ${FUNCTION} - not found")
set(${VARIABLE} "" CACHE INTERNAL "Have Fortran function ${FUNCTION}")
file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
"Determining if the Fortran ${FUNCTION} exists failed with the following output:\n"
"${OUTPUT}\n\n")
endif()
endif()
endmacro()
leela-zero-0.17/cmake/Modules/CheckFunctionExists.cmake 0000664 0000000 0000000 00000007275 13451323157 0023134 0 ustar 00root root 0000000 0000000 # Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.
#.rst:
# CheckFunctionExists
# -------------------
#
# Check if a C function can be linked::
#
# check_function_exists()
#
# Check that the ```` is provided by libraries on the system and store
# the result in a ````. ```` will be created as an internal
# cache variable.
#
# The following variables may be set before calling this macro to modify the
# way the check is run:
#
# ::
#
# CMAKE_REQUIRED_FLAGS = string of compile command line flags
# CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
# CMAKE_REQUIRED_INCLUDES = list of include directories
# CMAKE_REQUIRED_LIBRARIES = list of libraries to link
# CMAKE_REQUIRED_QUIET = execute quietly without messages
#
# .. note::
#
# Prefer using :Module:`CheckSymbolExists` instead of this module,
# for the following reasons:
#
# * ``check_function_exists()`` can't detect functions that are inlined
# in headers or specified as a macro.
#
# * ``check_function_exists()`` can't detect anything in the 32-bit
# versions of the Win32 API, because of a mismatch in calling conventions.
#
# * ``check_function_exists()`` only verifies linking, it does not verify
# that the function is declared in system headers.
macro(CHECK_FUNCTION_EXISTS FUNCTION VARIABLE)
if(NOT DEFINED "${VARIABLE}" OR "x${${VARIABLE}}" STREQUAL "x${VARIABLE}")
set(MACRO_CHECK_FUNCTION_DEFINITIONS
"-DCHECK_FUNCTION_EXISTS=${FUNCTION} ${CMAKE_REQUIRED_FLAGS}")
if(NOT CMAKE_REQUIRED_QUIET)
message(STATUS "Looking for ${FUNCTION}")
endif()
if(CMAKE_REQUIRED_LIBRARIES)
set(CHECK_FUNCTION_EXISTS_ADD_LIBRARIES
LINK_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES})
else()
set(CHECK_FUNCTION_EXISTS_ADD_LIBRARIES)
endif()
if(CMAKE_REQUIRED_INCLUDES)
set(CHECK_FUNCTION_EXISTS_ADD_INCLUDES
"-DINCLUDE_DIRECTORIES:STRING=${CMAKE_REQUIRED_INCLUDES}")
else()
set(CHECK_FUNCTION_EXISTS_ADD_INCLUDES)
endif()
if(CMAKE_C_COMPILER_LOADED)
set(_cfe_source ${CMAKE_ROOT}/Modules/CheckFunctionExists.c)
elseif(CMAKE_CXX_COMPILER_LOADED)
set(_cfe_source ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CheckFunctionExists/CheckFunctionExists.cxx)
configure_file(${CMAKE_ROOT}/Modules/CheckFunctionExists.c "${_cfe_source}" COPYONLY)
else()
message(FATAL_ERROR "CHECK_FUNCTION_EXISTS needs either C or CXX language enabled")
endif()
try_compile(${VARIABLE}
${CMAKE_BINARY_DIR}
${_cfe_source}
COMPILE_DEFINITIONS ${CMAKE_REQUIRED_DEFINITIONS}
${CHECK_FUNCTION_EXISTS_ADD_LIBRARIES}
CMAKE_FLAGS -DCOMPILE_DEFINITIONS:STRING=${MACRO_CHECK_FUNCTION_DEFINITIONS}
"${CHECK_FUNCTION_EXISTS_ADD_INCLUDES}"
OUTPUT_VARIABLE OUTPUT)
unset(_cfe_source)
if(${VARIABLE})
set(${VARIABLE} 1 CACHE INTERNAL "Have function ${FUNCTION}")
if(NOT CMAKE_REQUIRED_QUIET)
message(STATUS "Looking for ${FUNCTION} - found")
endif()
file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log
"Determining if the function ${FUNCTION} exists passed with the following output:\n"
"${OUTPUT}\n\n")
else()
if(NOT CMAKE_REQUIRED_QUIET)
message(STATUS "Looking for ${FUNCTION} - not found")
endif()
set(${VARIABLE} "" CACHE INTERNAL "Have function ${FUNCTION}")
file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
"Determining if the function ${FUNCTION} exists failed with the following output:\n"
"${OUTPUT}\n\n")
endif()
endif()
endmacro()
leela-zero-0.17/cmake/Modules/FindBLAS.cmake 0000664 0000000 0000000 00000046145 13451323157 0020532 0 ustar 00root root 0000000 0000000 # Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.
#.rst:
# FindBLAS
# --------
#
# Find BLAS library
#
# This module finds an installed fortran library that implements the
# BLAS linear-algebra interface (see http://www.netlib.org/blas/). The
# list of libraries searched for is taken from the autoconf macro file,
# acx_blas.m4 (distributed at
# http://ac-archive.sourceforge.net/ac-archive/acx_blas.html).
#
# This module sets the following variables:
#
# ::
#
# BLAS_FOUND - set to true if a library implementing the BLAS interface
# is found
# BLAS_LINKER_FLAGS - uncached list of required linker flags (excluding -l
# and -L).
# BLAS_LIBRARIES - uncached list of libraries (using full path name) to
# link against to use BLAS
# BLAS95_LIBRARIES - uncached list of libraries (using full path name)
# to link against to use BLAS95 interface
# BLAS95_FOUND - set to true if a library implementing the BLAS f95 interface
# is found
# BLA_STATIC if set on this determines what kind of linkage we do (static)
# BLA_VENDOR if set checks only the specified vendor, if not set checks
# all the possibilities
# BLA_F95 if set on tries to find the f95 interfaces for BLAS/LAPACK
#
# List of vendors (BLA_VENDOR) valid in this module:
#
# * Goto
# * OpenBLAS
# * ATLAS PhiPACK
# * CXML
# * DXML
# * SunPerf
# * SCSL
# * SGIMATH
# * IBMESSL
# * Intel10_32 (intel mkl v10 32 bit)
# * Intel10_64lp (intel mkl v10 64 bit, lp thread model, lp64 model)
# * Intel10_64lp_seq (intel mkl v10 64 bit, sequential code, lp64 model)
# * Intel (older versions of mkl 32 and 64 bit)
# * ACML
# * ACML_MP
# * ACML_GPU
# * Apple
# * NAS
# * Generic
#
# .. note::
#
# C/CXX should be enabled to use Intel mkl
#
include(${CMAKE_CURRENT_LIST_DIR}/CheckFunctionExists.cmake)
include(${CMAKE_CURRENT_LIST_DIR}/CheckFortranFunctionExists.cmake)
include(${CMAKE_CURRENT_LIST_DIR}/CMakePushCheckState.cmake)
cmake_push_check_state()
set(CMAKE_REQUIRED_QUIET ${BLAS_FIND_QUIETLY})
set(_blas_ORIG_CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_FIND_LIBRARY_SUFFIXES})
# Check the language being used
if( NOT (CMAKE_C_COMPILER_LOADED OR CMAKE_CXX_COMPILER_LOADED OR CMAKE_Fortran_COMPILER_LOADED) )
if(BLAS_FIND_REQUIRED)
message(FATAL_ERROR "FindBLAS requires Fortran, C, or C++ to be enabled.")
else()
message(STATUS "Looking for BLAS... - NOT found (Unsupported languages)")
return()
endif()
endif()
macro(Check_Fortran_Libraries LIBRARIES _prefix _name _flags _list _thread)
# This macro checks for the existence of the combination of fortran libraries
# given by _list. If the combination is found, this macro checks (using the
# Check_Fortran_Function_Exists macro) whether can link against that library
# combination using the name of a routine given by _name using the linker
# flags given by _flags. If the combination of libraries is found and passes
# the link test, LIBRARIES is set to the list of complete library paths that
# have been found. Otherwise, LIBRARIES is set to FALSE.
# N.B. _prefix is the prefix applied to the names of all cached variables that
# are generated internally and marked advanced by this macro.
set(_libdir ${ARGN})
set(_libraries_work TRUE)
set(${LIBRARIES})
set(_combined_name)
if (NOT _libdir)
if (WIN32)
set(_libdir ENV LIB)
elseif (APPLE)
set(_libdir ENV DYLD_LIBRARY_PATH)
else ()
set(_libdir ENV LD_LIBRARY_PATH)
endif ()
endif ()
foreach(_library ${_list})
set(_combined_name ${_combined_name}_${_library})
if(_libraries_work)
if (BLA_STATIC)
if (WIN32)
set(CMAKE_FIND_LIBRARY_SUFFIXES .lib ${CMAKE_FIND_LIBRARY_SUFFIXES})
endif ()
if (APPLE)
set(CMAKE_FIND_LIBRARY_SUFFIXES .lib ${CMAKE_FIND_LIBRARY_SUFFIXES})
else ()
set(CMAKE_FIND_LIBRARY_SUFFIXES .a ${CMAKE_FIND_LIBRARY_SUFFIXES})
endif ()
else ()
if (CMAKE_SYSTEM_NAME STREQUAL "Linux")
# for ubuntu's libblas3gf and liblapack3gf packages
set(CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_FIND_LIBRARY_SUFFIXES} .so.3gf)
endif ()
endif ()
find_library(${_prefix}_${_library}_LIBRARY
NAMES ${_library}
PATHS ${_libdir}
)
mark_as_advanced(${_prefix}_${_library}_LIBRARY)
set(${LIBRARIES} ${${LIBRARIES}} ${${_prefix}_${_library}_LIBRARY})
set(_libraries_work ${${_prefix}_${_library}_LIBRARY})
endif()
endforeach()
if(_libraries_work)
# Test this combination of libraries.
set(CMAKE_REQUIRED_LIBRARIES ${_flags} ${${LIBRARIES}} ${_thread})
# message("DEBUG: CMAKE_REQUIRED_LIBRARIES = ${CMAKE_REQUIRED_LIBRARIES}")
if (CMAKE_Fortran_COMPILER_LOADED)
check_fortran_function_exists("${_name}" ${_prefix}${_combined_name}_WORKS)
else()
check_function_exists("${_name}_" ${_prefix}${_combined_name}_WORKS)
endif()
set(CMAKE_REQUIRED_LIBRARIES)
mark_as_advanced(${_prefix}${_combined_name}_WORKS)
set(_libraries_work ${${_prefix}${_combined_name}_WORKS})
endif()
if(NOT _libraries_work)
set(${LIBRARIES} FALSE)
endif()
#message("DEBUG: ${LIBRARIES} = ${${LIBRARIES}}")
endmacro()
set(BLAS_LINKER_FLAGS)
set(BLAS_LIBRARIES)
set(BLAS95_LIBRARIES)
if (NOT $ENV{BLA_VENDOR} STREQUAL "")
set(BLA_VENDOR $ENV{BLA_VENDOR})
else ()
if(NOT BLA_VENDOR)
set(BLA_VENDOR "All")
endif()
endif ()
if (BLA_VENDOR STREQUAL "Goto" OR BLA_VENDOR STREQUAL "All")
if(NOT BLAS_LIBRARIES)
# gotoblas (http://www.tacc.utexas.edu/tacc-projects/gotoblas2)
check_fortran_libraries(
BLAS_LIBRARIES
BLAS
sgemm
""
"goto2"
""
)
endif()
endif ()
if (BLA_VENDOR STREQUAL "OpenBLAS" OR BLA_VENDOR STREQUAL "All")
if(NOT BLAS_LIBRARIES)
# OpenBLAS (http://www.openblas.net)
check_fortran_libraries(
BLAS_LIBRARIES
BLAS
sgemm
""
"openblas"
""
)
endif()
endif ()
if (BLA_VENDOR STREQUAL "ATLAS" OR BLA_VENDOR STREQUAL "All")
if(NOT BLAS_LIBRARIES)
# BLAS in ATLAS library? (http://math-atlas.sourceforge.net/)
check_fortran_libraries(
BLAS_LIBRARIES
BLAS
dgemm
""
"f77blas;atlas"
""
)
endif()
endif ()
# BLAS in PhiPACK libraries? (requires generic BLAS lib, too)
if (BLA_VENDOR STREQUAL "PhiPACK" OR BLA_VENDOR STREQUAL "All")
if(NOT BLAS_LIBRARIES)
check_fortran_libraries(
BLAS_LIBRARIES
BLAS
sgemm
""
"sgemm;dgemm;blas"
""
)
endif()
endif ()
# BLAS in Alpha CXML library?
if (BLA_VENDOR STREQUAL "CXML" OR BLA_VENDOR STREQUAL "All")
if(NOT BLAS_LIBRARIES)
check_fortran_libraries(
BLAS_LIBRARIES
BLAS
sgemm
""
"cxml"
""
)
endif()
endif ()
# BLAS in Alpha DXML library? (now called CXML, see above)
if (BLA_VENDOR STREQUAL "DXML" OR BLA_VENDOR STREQUAL "All")
if(NOT BLAS_LIBRARIES)
check_fortran_libraries(
BLAS_LIBRARIES
BLAS
sgemm
""
"dxml"
""
)
endif()
endif ()
# BLAS in Sun Performance library?
if (BLA_VENDOR STREQUAL "SunPerf" OR BLA_VENDOR STREQUAL "All")
if(NOT BLAS_LIBRARIES)
check_fortran_libraries(
BLAS_LIBRARIES
BLAS
sgemm
"-xlic_lib=sunperf"
"sunperf;sunmath"
""
)
if(BLAS_LIBRARIES)
set(BLAS_LINKER_FLAGS "-xlic_lib=sunperf")
endif()
endif()
endif ()
# BLAS in SCSL library? (SGI/Cray Scientific Library)
if (BLA_VENDOR STREQUAL "SCSL" OR BLA_VENDOR STREQUAL "All")
if(NOT BLAS_LIBRARIES)
check_fortran_libraries(
BLAS_LIBRARIES
BLAS
sgemm
""
"scsl"
""
)
endif()
endif ()
# BLAS in SGIMATH library?
if (BLA_VENDOR STREQUAL "SGIMATH" OR BLA_VENDOR STREQUAL "All")
if(NOT BLAS_LIBRARIES)
check_fortran_libraries(
BLAS_LIBRARIES
BLAS
sgemm
""
"complib.sgimath"
""
)
endif()
endif ()
# BLAS in IBM ESSL library? (requires generic BLAS lib, too)
if (BLA_VENDOR STREQUAL "IBMESSL" OR BLA_VENDOR STREQUAL "All")
if(NOT BLAS_LIBRARIES)
check_fortran_libraries(
BLAS_LIBRARIES
BLAS
sgemm
""
"essl;blas"
""
)
endif()
endif ()
#BLAS in acml library?
if (BLA_VENDOR MATCHES "ACML" OR BLA_VENDOR STREQUAL "All")
if( ((BLA_VENDOR STREQUAL "ACML") AND (NOT BLAS_ACML_LIB_DIRS)) OR
((BLA_VENDOR STREQUAL "ACML_MP") AND (NOT BLAS_ACML_MP_LIB_DIRS)) OR
((BLA_VENDOR STREQUAL "ACML_GPU") AND (NOT BLAS_ACML_GPU_LIB_DIRS))
)
# try to find acml in "standard" paths
if( WIN32 )
file( GLOB _ACML_ROOT "C:/AMD/acml*/ACML-EULA.txt" )
else()
file( GLOB _ACML_ROOT "/opt/acml*/ACML-EULA.txt" )
endif()
if( WIN32 )
file( GLOB _ACML_GPU_ROOT "C:/AMD/acml*/GPGPUexamples" )
else()
file( GLOB _ACML_GPU_ROOT "/opt/acml*/GPGPUexamples" )
endif()
list(GET _ACML_ROOT 0 _ACML_ROOT)
list(GET _ACML_GPU_ROOT 0 _ACML_GPU_ROOT)
if( _ACML_ROOT )
get_filename_component( _ACML_ROOT ${_ACML_ROOT} PATH )
if( SIZEOF_INTEGER EQUAL 8 )
set( _ACML_PATH_SUFFIX "_int64" )
else()
set( _ACML_PATH_SUFFIX "" )
endif()
if( CMAKE_Fortran_COMPILER_ID STREQUAL "Intel" )
set( _ACML_COMPILER32 "ifort32" )
set( _ACML_COMPILER64 "ifort64" )
elseif( CMAKE_Fortran_COMPILER_ID STREQUAL "SunPro" )
set( _ACML_COMPILER32 "sun32" )
set( _ACML_COMPILER64 "sun64" )
elseif( CMAKE_Fortran_COMPILER_ID STREQUAL "PGI" )
set( _ACML_COMPILER32 "pgi32" )
if( WIN32 )
set( _ACML_COMPILER64 "win64" )
else()
set( _ACML_COMPILER64 "pgi64" )
endif()
elseif( CMAKE_Fortran_COMPILER_ID STREQUAL "Open64" )
# 32 bit builds not supported on Open64 but for code simplicity
# We'll just use the same directory twice
set( _ACML_COMPILER32 "open64_64" )
set( _ACML_COMPILER64 "open64_64" )
elseif( CMAKE_Fortran_COMPILER_ID STREQUAL "NAG" )
set( _ACML_COMPILER32 "nag32" )
set( _ACML_COMPILER64 "nag64" )
else()
set( _ACML_COMPILER32 "gfortran32" )
set( _ACML_COMPILER64 "gfortran64" )
endif()
if( BLA_VENDOR STREQUAL "ACML_MP" )
set(_ACML_MP_LIB_DIRS
"${_ACML_ROOT}/${_ACML_COMPILER32}_mp${_ACML_PATH_SUFFIX}/lib"
"${_ACML_ROOT}/${_ACML_COMPILER64}_mp${_ACML_PATH_SUFFIX}/lib" )
else()
set(_ACML_LIB_DIRS
"${_ACML_ROOT}/${_ACML_COMPILER32}${_ACML_PATH_SUFFIX}/lib"
"${_ACML_ROOT}/${_ACML_COMPILER64}${_ACML_PATH_SUFFIX}/lib" )
endif()
endif()
elseif(BLAS_${BLA_VENDOR}_LIB_DIRS)
set(_${BLA_VENDOR}_LIB_DIRS ${BLAS_${BLA_VENDOR}_LIB_DIRS})
endif()
if( BLA_VENDOR STREQUAL "ACML_MP" )
foreach( BLAS_ACML_MP_LIB_DIRS ${_ACML_MP_LIB_DIRS})
check_fortran_libraries (
BLAS_LIBRARIES
BLAS
sgemm
"" "acml_mp;acml_mv" "" ${BLAS_ACML_MP_LIB_DIRS}
)
if( BLAS_LIBRARIES )
break()
endif()
endforeach()
elseif( BLA_VENDOR STREQUAL "ACML_GPU" )
foreach( BLAS_ACML_GPU_LIB_DIRS ${_ACML_GPU_LIB_DIRS})
check_fortran_libraries (
BLAS_LIBRARIES
BLAS
sgemm
"" "acml;acml_mv;CALBLAS" "" ${BLAS_ACML_GPU_LIB_DIRS}
)
if( BLAS_LIBRARIES )
break()
endif()
endforeach()
else()
foreach( BLAS_ACML_LIB_DIRS ${_ACML_LIB_DIRS} )
check_fortran_libraries (
BLAS_LIBRARIES
BLAS
sgemm
"" "acml;acml_mv" "" ${BLAS_ACML_LIB_DIRS}
)
if( BLAS_LIBRARIES )
break()
endif()
endforeach()
endif()
# Either acml or acml_mp should be in LD_LIBRARY_PATH but not both
if(NOT BLAS_LIBRARIES)
check_fortran_libraries(
BLAS_LIBRARIES
BLAS
sgemm
""
"acml;acml_mv"
""
)
endif()
if(NOT BLAS_LIBRARIES)
check_fortran_libraries(
BLAS_LIBRARIES
BLAS
sgemm
""
"acml_mp;acml_mv"
""
)
endif()
if(NOT BLAS_LIBRARIES)
check_fortran_libraries(
BLAS_LIBRARIES
BLAS
sgemm
""
"acml;acml_mv;CALBLAS"
""
)
endif()
endif () # ACML
# Apple BLAS library?
if (BLA_VENDOR STREQUAL "Apple" OR BLA_VENDOR STREQUAL "All")
if(NOT BLAS_LIBRARIES)
check_fortran_libraries(
BLAS_LIBRARIES
BLAS
dgemm
""
"Accelerate"
""
)
endif()
endif ()
if (BLA_VENDOR STREQUAL "NAS" OR BLA_VENDOR STREQUAL "All")
if ( NOT BLAS_LIBRARIES )
check_fortran_libraries(
BLAS_LIBRARIES
BLAS
dgemm
""
"vecLib"
""
)
endif ()
endif ()
# Generic BLAS library?
if (BLA_VENDOR STREQUAL "Generic" OR BLA_VENDOR STREQUAL "All")
if(NOT BLAS_LIBRARIES)
check_fortran_libraries(
BLAS_LIBRARIES
BLAS
sgemm
""
"blas"
""
)
endif()
endif ()
#BLAS in intel mkl 10 library? (em64t 64bit)
if (BLA_VENDOR MATCHES "Intel" OR BLA_VENDOR STREQUAL "All")
if (NOT WIN32)
set(LM "-lm")
endif ()
if (CMAKE_C_COMPILER_LOADED OR CMAKE_CXX_COMPILER_LOADED)
if(BLAS_FIND_QUIETLY OR NOT BLAS_FIND_REQUIRED)
find_package(Threads)
else()
find_package(Threads REQUIRED)
endif()
set(BLAS_SEARCH_LIBS "")
if(BLA_F95)
set(BLAS_mkl_SEARCH_SYMBOL SGEMM)
set(_LIBRARIES BLAS95_LIBRARIES)
if (WIN32)
if (BLA_STATIC)
set(BLAS_mkl_DLL_SUFFIX "")
else()
set(BLAS_mkl_DLL_SUFFIX "_dll")
endif()
# Find the main file (32-bit or 64-bit)
set(BLAS_SEARCH_LIBS_WIN_MAIN "")
if (BLA_VENDOR STREQUAL "Intel10_32" OR BLA_VENDOR STREQUAL "All")
list(APPEND BLAS_SEARCH_LIBS_WIN_MAIN
"mkl_blas95${BLAS_mkl_DLL_SUFFIX} mkl_intel_c${BLAS_mkl_DLL_SUFFIX}")
endif()
if (BLA_VENDOR MATCHES "^Intel10_64lp" OR BLA_VENDOR STREQUAL "All")
list(APPEND BLAS_SEARCH_LIBS_WIN_MAIN
"mkl_blas95_lp64${BLAS_mkl_DLL_SUFFIX} mkl_intel_lp64${BLAS_mkl_DLL_SUFFIX}")
endif ()
# Add threading/sequential libs
set(BLAS_SEARCH_LIBS_WIN_THREAD "")
if (BLA_VENDOR MATCHES "_seq$" OR BLA_VENDOR STREQUAL "All")
list(APPEND BLAS_SEARCH_LIBS_WIN_THREAD
"mkl_sequential${BLAS_mkl_DLL_SUFFIX}")
endif()
if (NOT BLA_VENDOR MATCHES "_seq$" OR BLA_VENDOR STREQUAL "All")
# old version
list(APPEND BLAS_SEARCH_LIBS_WIN_THREAD
"libguide40 mkl_intel_thread${BLAS_mkl_DLL_SUFFIX}")
# mkl >= 10.3
list(APPEND BLAS_SEARCH_LIBS_WIN_THREAD
"libiomp5md mkl_intel_thread${BLAS_mkl_DLL_SUFFIX}")
endif()
# Cartesian product of the above
foreach (MAIN ${BLAS_SEARCH_LIBS_WIN_MAIN})
foreach (THREAD ${BLAS_SEARCH_LIBS_WIN_THREAD})
list(APPEND BLAS_SEARCH_LIBS
"${MAIN} ${THREAD} mkl_core${BLAS_mkl_DLL_SUFFIX}")
endforeach()
endforeach()
else ()
if (BLA_VENDOR STREQUAL "Intel10_32" OR BLA_VENDOR STREQUAL "All")
list(APPEND BLAS_SEARCH_LIBS
"mkl_blas95 mkl_intel mkl_intel_thread mkl_core guide")
endif ()
if (BLA_VENDOR STREQUAL "Intel10_64lp" OR BLA_VENDOR STREQUAL "All")
# old version
list(APPEND BLAS_SEARCH_LIBS
"mkl_blas95 mkl_intel_lp64 mkl_intel_thread mkl_core guide")
# mkl >= 10.3
if (CMAKE_C_COMPILER MATCHES ".+gcc")
list(APPEND BLAS_SEARCH_LIBS
"mkl_blas95_lp64 mkl_intel_lp64 mkl_gnu_thread mkl_core gomp")
else ()
list(APPEND BLAS_SEARCH_LIBS
"mkl_blas95_lp64 mkl_intel_lp64 mkl_intel_thread mkl_core iomp5")
endif ()
endif ()
if (BLA_VENDOR STREQUAL "Intel10_64lp_seq" OR BLA_VENDOR STREQUAL "All")
list(APPEND BLAS_SEARCH_LIBS
"mkl_intel_lp64 mkl_sequential mkl_core")
endif ()
endif ()
else ()
set(BLAS_mkl_SEARCH_SYMBOL sgemm)
set(_LIBRARIES BLAS_LIBRARIES)
if (WIN32)
if (BLA_STATIC)
set(BLAS_mkl_DLL_SUFFIX "")
else()
set(BLAS_mkl_DLL_SUFFIX "_dll")
endif()
# Find the main file (32-bit or 64-bit)
set(BLAS_SEARCH_LIBS_WIN_MAIN "")
if (BLA_VENDOR STREQUAL "Intel10_32" OR BLA_VENDOR STREQUAL "All")
list(APPEND BLAS_SEARCH_LIBS_WIN_MAIN
"mkl_intel_c${BLAS_mkl_DLL_SUFFIX}")
endif()
if (BLA_VENDOR MATCHES "^Intel10_64lp" OR BLA_VENDOR STREQUAL "All")
list(APPEND BLAS_SEARCH_LIBS_WIN_MAIN
"mkl_intel_lp64${BLAS_mkl_DLL_SUFFIX}")
endif ()
# Add threading/sequential libs
set(BLAS_SEARCH_LIBS_WIN_THREAD "")
if (NOT BLA_VENDOR MATCHES "_seq$" OR BLA_VENDOR STREQUAL "All")
# old version
list(APPEND BLAS_SEARCH_LIBS_WIN_THREAD
"libguide40 mkl_intel_thread${BLAS_mkl_DLL_SUFFIX}")
# mkl >= 10.3
list(APPEND BLAS_SEARCH_LIBS_WIN_THREAD
"libiomp5md mkl_intel_thread${BLAS_mkl_DLL_SUFFIX}")
endif()
if (BLA_VENDOR MATCHES "_seq$" OR BLA_VENDOR STREQUAL "All")
list(APPEND BLAS_SEARCH_LIBS_WIN_THREAD
"mkl_sequential${BLAS_mkl_DLL_SUFFIX}")
endif()
# Cartesian product of the above
foreach (MAIN ${BLAS_SEARCH_LIBS_WIN_MAIN})
foreach (THREAD ${BLAS_SEARCH_LIBS_WIN_THREAD})
list(APPEND BLAS_SEARCH_LIBS
"${MAIN} ${THREAD} mkl_core${BLAS_mkl_DLL_SUFFIX}")
endforeach()
endforeach()
else ()
if (BLA_VENDOR STREQUAL "Intel10_32" OR BLA_VENDOR STREQUAL "All")
list(APPEND BLAS_SEARCH_LIBS
"mkl_intel mkl_intel_thread mkl_core guide")
endif ()
if (BLA_VENDOR STREQUAL "Intel10_64lp" OR BLA_VENDOR STREQUAL "All")
# old version
list(APPEND BLAS_SEARCH_LIBS
"mkl_intel_lp64 mkl_intel_thread mkl_core guide")
# mkl >= 10.3
if (CMAKE_C_COMPILER MATCHES ".+gcc")
list(APPEND BLAS_SEARCH_LIBS
"mkl_intel_lp64 mkl_gnu_thread mkl_core gomp")
else ()
list(APPEND BLAS_SEARCH_LIBS
"mkl_intel_lp64 mkl_intel_thread mkl_core iomp5")
endif ()
endif ()
if (BLA_VENDOR STREQUAL "Intel10_64lp_seq" OR BLA_VENDOR STREQUAL "All")
list(APPEND BLAS_SEARCH_LIBS
"mkl_intel_lp64 mkl_sequential mkl_core")
endif ()
#older vesions of intel mkl libs
if (BLA_VENDOR STREQUAL "Intel" OR BLA_VENDOR STREQUAL "All")
list(APPEND BLAS_SEARCH_LIBS
"mkl")
list(APPEND BLAS_SEARCH_LIBS
"mkl_ia32")
list(APPEND BLAS_SEARCH_LIBS
"mkl_em64t")
endif ()
endif ()
endif ()
foreach (IT ${BLAS_SEARCH_LIBS})
string(REPLACE " " ";" SEARCH_LIBS ${IT})
if (${_LIBRARIES})
else ()
check_fortran_libraries(
${_LIBRARIES}
BLAS
${BLAS_mkl_SEARCH_SYMBOL}
""
"${SEARCH_LIBS}"
"${CMAKE_THREAD_LIBS_INIT};${LM}"
)
endif ()
endforeach ()
endif ()
endif ()
if(BLA_F95)
if(BLAS95_LIBRARIES)
set(BLAS95_FOUND TRUE)
else()
set(BLAS95_FOUND FALSE)
endif()
if(NOT BLAS_FIND_QUIETLY)
if(BLAS95_FOUND)
message(STATUS "A library with BLAS95 API found.")
else()
if(BLAS_FIND_REQUIRED)
message(FATAL_ERROR
"A required library with BLAS95 API not found. Please specify library location.")
else()
message(STATUS
"A library with BLAS95 API not found. Please specify library location.")
endif()
endif()
endif()
set(BLAS_FOUND TRUE)
set(BLAS_LIBRARIES "${BLAS95_LIBRARIES}")
else()
if(BLAS_LIBRARIES)
set(BLAS_FOUND TRUE)
else()
set(BLAS_FOUND FALSE)
endif()
if(NOT BLAS_FIND_QUIETLY)
if(BLAS_FOUND)
message(STATUS "A library with BLAS API found.")
else()
if(BLAS_FIND_REQUIRED)
message(FATAL_ERROR
"A required library with BLAS API not found. Please specify library location."
)
else()
message(STATUS
"A library with BLAS API not found. Please specify library location."
)
endif()
endif()
endif()
endif()
cmake_pop_check_state()
set(CMAKE_FIND_LIBRARY_SUFFIXES ${_blas_ORIG_CMAKE_FIND_LIBRARY_SUFFIXES})
leela-zero-0.17/cmake/Modules/FindOpenCL.cmake 0000664 0000000 0000000 00000010324 13451323157 0021117 0 ustar 00root root 0000000 0000000 # Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.
#.rst:
# FindOpenCL
# ----------
#
# Try to find OpenCL
#
# IMPORTED Targets
# ^^^^^^^^^^^^^^^^
#
# This module defines :prop_tgt:`IMPORTED` target ``OpenCL::OpenCL``, if
# OpenCL has been found.
#
# Result Variables
# ^^^^^^^^^^^^^^^^
#
# This module defines the following variables::
#
# OpenCL_FOUND - True if OpenCL was found
# OpenCL_INCLUDE_DIRS - include directories for OpenCL
# OpenCL_LIBRARIES - link against this library to use OpenCL
# OpenCL_VERSION_STRING - Highest supported OpenCL version (eg. 1.2)
# OpenCL_VERSION_MAJOR - The major version of the OpenCL implementation
# OpenCL_VERSION_MINOR - The minor version of the OpenCL implementation
#
# The module will also define two cache variables::
#
# OpenCL_INCLUDE_DIR - the OpenCL include directory
# OpenCL_LIBRARY - the path to the OpenCL library
#
function(_FIND_OPENCL_VERSION)
include(CheckSymbolExists)
include(CMakePushCheckState)
set(CMAKE_REQUIRED_QUIET ${OpenCL_FIND_QUIETLY})
CMAKE_PUSH_CHECK_STATE()
foreach(VERSION "2_2" "2_1" "2_0" "1_2" "1_1" "1_0")
set(CMAKE_REQUIRED_INCLUDES "${OpenCL_INCLUDE_DIR}")
if(APPLE)
CHECK_SYMBOL_EXISTS(
CL_VERSION_${VERSION}
"${OpenCL_INCLUDE_DIR}/Headers/cl.h"
OPENCL_VERSION_${VERSION})
else()
CHECK_SYMBOL_EXISTS(
CL_VERSION_${VERSION}
"${OpenCL_INCLUDE_DIR}/CL/cl.h"
OPENCL_VERSION_${VERSION})
endif()
if(OPENCL_VERSION_${VERSION})
string(REPLACE "_" "." VERSION "${VERSION}")
set(OpenCL_VERSION_STRING ${VERSION} PARENT_SCOPE)
string(REGEX MATCHALL "[0-9]+" version_components "${VERSION}")
list(GET version_components 0 major_version)
list(GET version_components 1 minor_version)
set(OpenCL_VERSION_MAJOR ${major_version} PARENT_SCOPE)
set(OpenCL_VERSION_MINOR ${minor_version} PARENT_SCOPE)
break()
endif()
endforeach()
CMAKE_POP_CHECK_STATE()
endfunction()
find_path(OpenCL_INCLUDE_DIR
NAMES
CL/cl.h OpenCL/cl.h
PATHS
ENV "PROGRAMFILES(X86)"
ENV AMDAPPSDKROOT
ENV INTELOCLSDKROOT
ENV NVSDKCOMPUTE_ROOT
ENV CUDA_PATH
ENV ATISTREAMSDKROOT
PATH_SUFFIXES
include
OpenCL/common/inc
"AMD APP/include")
_FIND_OPENCL_VERSION()
if(WIN32)
if(CMAKE_SIZEOF_VOID_P EQUAL 4)
find_library(OpenCL_LIBRARY
NAMES OpenCL
PATHS
ENV "PROGRAMFILES(X86)"
ENV AMDAPPSDKROOT
ENV INTELOCLSDKROOT
ENV CUDA_PATH
ENV NVSDKCOMPUTE_ROOT
ENV ATISTREAMSDKROOT
PATH_SUFFIXES
"AMD APP/lib/x86"
lib/x86
lib/Win32
OpenCL/common/lib/Win32)
elseif(CMAKE_SIZEOF_VOID_P EQUAL 8)
find_library(OpenCL_LIBRARY
NAMES OpenCL
PATHS
ENV "PROGRAMFILES(X86)"
ENV AMDAPPSDKROOT
ENV INTELOCLSDKROOT
ENV CUDA_PATH
ENV NVSDKCOMPUTE_ROOT
ENV ATISTREAMSDKROOT
PATH_SUFFIXES
"AMD APP/lib/x86_64"
lib/x86_64
lib/x64
OpenCL/common/lib/x64)
endif()
else()
find_library(OpenCL_LIBRARY
NAMES OpenCL
PATHS
ENV AMDAPPSDKROOT
ENV CUDA_PATH
PATH_SUFFIXES
lib/x86_64
lib/x64
lib
lib64)
endif()
set(OpenCL_LIBRARIES ${OpenCL_LIBRARY})
set(OpenCL_INCLUDE_DIRS ${OpenCL_INCLUDE_DIR})
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
find_package_handle_standard_args(
OpenCL
FOUND_VAR OpenCL_FOUND
REQUIRED_VARS OpenCL_LIBRARY OpenCL_INCLUDE_DIR
VERSION_VAR OpenCL_VERSION_STRING)
mark_as_advanced(
OpenCL_INCLUDE_DIR
OpenCL_LIBRARY)
if(OpenCL_FOUND AND NOT TARGET OpenCL::OpenCL)
if(OpenCL_LIBRARY MATCHES "/([^/]+)\\.framework$")
add_library(OpenCL::OpenCL INTERFACE IMPORTED)
set_target_properties(OpenCL::OpenCL PROPERTIES
INTERFACE_LINK_LIBRARIES "${OpenCL_LIBRARY}")
else()
add_library(OpenCL::OpenCL UNKNOWN IMPORTED)
set_target_properties(OpenCL::OpenCL PROPERTIES
IMPORTED_LOCATION "${OpenCL_LIBRARY}")
endif()
set_target_properties(OpenCL::OpenCL PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES "${OpenCL_INCLUDE_DIRS}")
endif()
leela-zero-0.17/cmake/Modules/FindPackageHandleStandardArgs.cmake 0000664 0000000 0000000 00000035066 13451323157 0024756 0 ustar 00root root 0000000 0000000 # Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.
#[=======================================================================[.rst:
FindPackageHandleStandardArgs
-----------------------------
This module provides a function intended to be used in :ref:`Find Modules`
implementing :command:`find_package()` calls. It handles the
``REQUIRED``, ``QUIET`` and version-related arguments of ``find_package``.
It also sets the ``_FOUND`` variable. The package is
considered found if all variables listed contain valid results, e.g.
valid filepaths.
.. command:: find_package_handle_standard_args
There are two signatures::
find_package_handle_standard_args(
(DEFAULT_MSG|)
...
)
find_package_handle_standard_args(
[FOUND_VAR ]
[REQUIRED_VARS ...]
[VERSION_VAR ]
[HANDLE_COMPONENTS]
[CONFIG_MODE]
[FAIL_MESSAGE ]
)
The ``_FOUND`` variable will be set to ``TRUE`` if all
the variables ``...`` are valid and any optional
constraints are satisfied, and ``FALSE`` otherwise. A success or
failure message may be displayed based on the results and on
whether the ``REQUIRED`` and/or ``QUIET`` option was given to
the :command:`find_package` call.
The options are:
``(DEFAULT_MSG|)``
In the simple signature this specifies the failure message.
Use ``DEFAULT_MSG`` to ask for a default message to be computed
(recommended). Not valid in the full signature.
``FOUND_VAR ``
Obsolete. Specifies either ``_FOUND`` or
``_FOUND`` as the result variable. This exists only
for compatibility with older versions of CMake and is now ignored.
Result variables of both names are always set for compatibility.
``REQUIRED_VARS ...``
Specify the variables which are required for this package.
These may be named in the generated failure message asking the
user to set the missing variable values. Therefore these should
typically be cache entries such as ``FOO_LIBRARY`` and not output
variables like ``FOO_LIBRARIES``.
``VERSION_VAR ``
Specify the name of a variable that holds the version of the package
that has been found. This version will be checked against the
(potentially) specified required version given to the
:command:`find_package` call, including its ``EXACT`` option.
The default messages include information about the required
version and the version which has been actually found, both
if the version is ok or not.
``HANDLE_COMPONENTS``
Enable handling of package components. In this case, the command
will report which components have been found and which are missing,
and the ``_FOUND`` variable will be set to ``FALSE``
if any of the required components (i.e. not the ones listed after
the ``OPTIONAL_COMPONENTS`` option of :command:`find_package`) are
missing.
``CONFIG_MODE``
Specify that the calling find module is a wrapper around a
call to ``find_package( NO_MODULE)``. This implies
a ``VERSION_VAR`` value of ``_VERSION``. The command
will automatically check whether the package configuration file
was found.
``FAIL_MESSAGE ``
Specify a custom failure message instead of using the default
generated message. Not recommended.
Example for the simple signature:
.. code-block:: cmake
find_package_handle_standard_args(LibXml2 DEFAULT_MSG
LIBXML2_LIBRARY LIBXML2_INCLUDE_DIR)
The ``LibXml2`` package is considered to be found if both
``LIBXML2_LIBRARY`` and ``LIBXML2_INCLUDE_DIR`` are valid.
Then also ``LibXml2_FOUND`` is set to ``TRUE``. If it is not found
and ``REQUIRED`` was used, it fails with a
:command:`message(FATAL_ERROR)`, independent whether ``QUIET`` was
used or not. If it is found, success will be reported, including
the content of the first ````. On repeated CMake runs,
the same message will not be printed again.
Example for the full signature:
.. code-block:: cmake
find_package_handle_standard_args(LibArchive
REQUIRED_VARS LibArchive_LIBRARY LibArchive_INCLUDE_DIR
VERSION_VAR LibArchive_VERSION)
In this case, the ``LibArchive`` package is considered to be found if
both ``LibArchive_LIBRARY`` and ``LibArchive_INCLUDE_DIR`` are valid.
Also the version of ``LibArchive`` will be checked by using the version
contained in ``LibArchive_VERSION``. Since no ``FAIL_MESSAGE`` is given,
the default messages will be printed.
Another example for the full signature:
.. code-block:: cmake
find_package(Automoc4 QUIET NO_MODULE HINTS /opt/automoc4)
find_package_handle_standard_args(Automoc4 CONFIG_MODE)
In this case, a ``FindAutmoc4.cmake`` module wraps a call to
``find_package(Automoc4 NO_MODULE)`` and adds an additional search
directory for ``automoc4``. Then the call to
``find_package_handle_standard_args`` produces a proper success/failure
message.
#]=======================================================================]
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageMessage.cmake)
# internal helper macro
macro(_FPHSA_FAILURE_MESSAGE _msg)
if (${_NAME}_FIND_REQUIRED)
message(FATAL_ERROR "${_msg}")
else ()
if (NOT ${_NAME}_FIND_QUIETLY)
message(STATUS "${_msg}")
endif ()
endif ()
endmacro()
# internal helper macro to generate the failure message when used in CONFIG_MODE:
macro(_FPHSA_HANDLE_FAILURE_CONFIG_MODE)
# _CONFIG is set, but FOUND is false, this means that some other of the REQUIRED_VARS was not found:
if(${_NAME}_CONFIG)
_FPHSA_FAILURE_MESSAGE("${FPHSA_FAIL_MESSAGE}: missing:${MISSING_VARS} (found ${${_NAME}_CONFIG} ${VERSION_MSG})")
else()
# If _CONSIDERED_CONFIGS is set, the config-file has been found, but no suitable version.
# List them all in the error message:
if(${_NAME}_CONSIDERED_CONFIGS)
set(configsText "")
list(LENGTH ${_NAME}_CONSIDERED_CONFIGS configsCount)
math(EXPR configsCount "${configsCount} - 1")
foreach(currentConfigIndex RANGE ${configsCount})
list(GET ${_NAME}_CONSIDERED_CONFIGS ${currentConfigIndex} filename)
list(GET ${_NAME}_CONSIDERED_VERSIONS ${currentConfigIndex} version)
string(APPEND configsText " ${filename} (version ${version})\n")
endforeach()
if (${_NAME}_NOT_FOUND_MESSAGE)
string(APPEND configsText " Reason given by package: ${${_NAME}_NOT_FOUND_MESSAGE}\n")
endif()
_FPHSA_FAILURE_MESSAGE("${FPHSA_FAIL_MESSAGE} ${VERSION_MSG}, checked the following files:\n${configsText}")
else()
# Simple case: No Config-file was found at all:
_FPHSA_FAILURE_MESSAGE("${FPHSA_FAIL_MESSAGE}: found neither ${_NAME}Config.cmake nor ${_NAME_LOWER}-config.cmake ${VERSION_MSG}")
endif()
endif()
endmacro()
function(FIND_PACKAGE_HANDLE_STANDARD_ARGS _NAME _FIRST_ARG)
# Set up the arguments for `cmake_parse_arguments`.
set(options CONFIG_MODE HANDLE_COMPONENTS)
set(oneValueArgs FAIL_MESSAGE VERSION_VAR FOUND_VAR)
set(multiValueArgs REQUIRED_VARS)
# Check whether we are in 'simple' or 'extended' mode:
set(_KEYWORDS_FOR_EXTENDED_MODE ${options} ${oneValueArgs} ${multiValueArgs} )
list(FIND _KEYWORDS_FOR_EXTENDED_MODE "${_FIRST_ARG}" INDEX)
if(${INDEX} EQUAL -1)
set(FPHSA_FAIL_MESSAGE ${_FIRST_ARG})
set(FPHSA_REQUIRED_VARS ${ARGN})
set(FPHSA_VERSION_VAR)
else()
cmake_parse_arguments(FPHSA "${options}" "${oneValueArgs}" "${multiValueArgs}" ${_FIRST_ARG} ${ARGN})
if(FPHSA_UNPARSED_ARGUMENTS)
message(FATAL_ERROR "Unknown keywords given to FIND_PACKAGE_HANDLE_STANDARD_ARGS(): \"${FPHSA_UNPARSED_ARGUMENTS}\"")
endif()
if(NOT FPHSA_FAIL_MESSAGE)
set(FPHSA_FAIL_MESSAGE "DEFAULT_MSG")
endif()
# In config-mode, we rely on the variable _CONFIG, which is set by find_package()
# when it successfully found the config-file, including version checking:
if(FPHSA_CONFIG_MODE)
list(INSERT FPHSA_REQUIRED_VARS 0 ${_NAME}_CONFIG)
list(REMOVE_DUPLICATES FPHSA_REQUIRED_VARS)
set(FPHSA_VERSION_VAR ${_NAME}_VERSION)
endif()
if(NOT FPHSA_REQUIRED_VARS)
message(FATAL_ERROR "No REQUIRED_VARS specified for FIND_PACKAGE_HANDLE_STANDARD_ARGS()")
endif()
endif()
# now that we collected all arguments, process them
if("x${FPHSA_FAIL_MESSAGE}" STREQUAL "xDEFAULT_MSG")
set(FPHSA_FAIL_MESSAGE "Could NOT find ${_NAME}")
endif()
list(GET FPHSA_REQUIRED_VARS 0 _FIRST_REQUIRED_VAR)
string(TOUPPER ${_NAME} _NAME_UPPER)
string(TOLOWER ${_NAME} _NAME_LOWER)
if(FPHSA_FOUND_VAR)
if(FPHSA_FOUND_VAR MATCHES "^${_NAME}_FOUND$" OR FPHSA_FOUND_VAR MATCHES "^${_NAME_UPPER}_FOUND$")
set(_FOUND_VAR ${FPHSA_FOUND_VAR})
else()
message(FATAL_ERROR "The argument for FOUND_VAR is \"${FPHSA_FOUND_VAR}\", but only \"${_NAME}_FOUND\" and \"${_NAME_UPPER}_FOUND\" are valid names.")
endif()
else()
set(_FOUND_VAR ${_NAME_UPPER}_FOUND)
endif()
# collect all variables which were not found, so they can be printed, so the
# user knows better what went wrong (#6375)
set(MISSING_VARS "")
set(DETAILS "")
# check if all passed variables are valid
set(FPHSA_FOUND_${_NAME} TRUE)
foreach(_CURRENT_VAR ${FPHSA_REQUIRED_VARS})
if(NOT ${_CURRENT_VAR})
set(FPHSA_FOUND_${_NAME} FALSE)
string(APPEND MISSING_VARS " ${_CURRENT_VAR}")
else()
string(APPEND DETAILS "[${${_CURRENT_VAR}}]")
endif()
endforeach()
if(FPHSA_FOUND_${_NAME})
set(${_NAME}_FOUND TRUE)
set(${_NAME_UPPER}_FOUND TRUE)
else()
set(${_NAME}_FOUND FALSE)
set(${_NAME_UPPER}_FOUND FALSE)
endif()
# component handling
unset(FOUND_COMPONENTS_MSG)
unset(MISSING_COMPONENTS_MSG)
if(FPHSA_HANDLE_COMPONENTS)
foreach(comp ${${_NAME}_FIND_COMPONENTS})
if(${_NAME}_${comp}_FOUND)
if(NOT DEFINED FOUND_COMPONENTS_MSG)
set(FOUND_COMPONENTS_MSG "found components: ")
endif()
string(APPEND FOUND_COMPONENTS_MSG " ${comp}")
else()
if(NOT DEFINED MISSING_COMPONENTS_MSG)
set(MISSING_COMPONENTS_MSG "missing components: ")
endif()
string(APPEND MISSING_COMPONENTS_MSG " ${comp}")
if(${_NAME}_FIND_REQUIRED_${comp})
set(${_NAME}_FOUND FALSE)
string(APPEND MISSING_VARS " ${comp}")
endif()
endif()
endforeach()
set(COMPONENT_MSG "${FOUND_COMPONENTS_MSG} ${MISSING_COMPONENTS_MSG}")
string(APPEND DETAILS "[c${COMPONENT_MSG}]")
endif()
# version handling:
set(VERSION_MSG "")
set(VERSION_OK TRUE)
# check with DEFINED here as the requested or found version may be "0"
if (DEFINED ${_NAME}_FIND_VERSION)
if(DEFINED ${FPHSA_VERSION_VAR})
set(_FOUND_VERSION ${${FPHSA_VERSION_VAR}})
if(${_NAME}_FIND_VERSION_EXACT) # exact version required
# count the dots in the version string
string(REGEX REPLACE "[^.]" "" _VERSION_DOTS "${_FOUND_VERSION}")
# add one dot because there is one dot more than there are components
string(LENGTH "${_VERSION_DOTS}." _VERSION_DOTS)
if (_VERSION_DOTS GREATER ${_NAME}_FIND_VERSION_COUNT)
# Because of the C++ implementation of find_package() ${_NAME}_FIND_VERSION_COUNT
# is at most 4 here. Therefore a simple lookup table is used.
if (${_NAME}_FIND_VERSION_COUNT EQUAL 1)
set(_VERSION_REGEX "[^.]*")
elseif (${_NAME}_FIND_VERSION_COUNT EQUAL 2)
set(_VERSION_REGEX "[^.]*\\.[^.]*")
elseif (${_NAME}_FIND_VERSION_COUNT EQUAL 3)
set(_VERSION_REGEX "[^.]*\\.[^.]*\\.[^.]*")
else ()
set(_VERSION_REGEX "[^.]*\\.[^.]*\\.[^.]*\\.[^.]*")
endif ()
string(REGEX REPLACE "^(${_VERSION_REGEX})\\..*" "\\1" _VERSION_HEAD "${_FOUND_VERSION}")
unset(_VERSION_REGEX)
if (NOT ${_NAME}_FIND_VERSION VERSION_EQUAL _VERSION_HEAD)
set(VERSION_MSG "Found unsuitable version \"${_FOUND_VERSION}\", but required is exact version \"${${_NAME}_FIND_VERSION}\"")
set(VERSION_OK FALSE)
else ()
set(VERSION_MSG "(found suitable exact version \"${_FOUND_VERSION}\")")
endif ()
unset(_VERSION_HEAD)
else ()
if (NOT ${_NAME}_FIND_VERSION VERSION_EQUAL _FOUND_VERSION)
set(VERSION_MSG "Found unsuitable version \"${_FOUND_VERSION}\", but required is exact version \"${${_NAME}_FIND_VERSION}\"")
set(VERSION_OK FALSE)
else ()
set(VERSION_MSG "(found suitable exact version \"${_FOUND_VERSION}\")")
endif ()
endif ()
unset(_VERSION_DOTS)
else() # minimum version specified:
if (${_NAME}_FIND_VERSION VERSION_GREATER _FOUND_VERSION)
set(VERSION_MSG "Found unsuitable version \"${_FOUND_VERSION}\", but required is at least \"${${_NAME}_FIND_VERSION}\"")
set(VERSION_OK FALSE)
else ()
set(VERSION_MSG "(found suitable version \"${_FOUND_VERSION}\", minimum required is \"${${_NAME}_FIND_VERSION}\")")
endif ()
endif()
else()
# if the package was not found, but a version was given, add that to the output:
if(${_NAME}_FIND_VERSION_EXACT)
set(VERSION_MSG "(Required is exact version \"${${_NAME}_FIND_VERSION}\")")
else()
set(VERSION_MSG "(Required is at least version \"${${_NAME}_FIND_VERSION}\")")
endif()
endif()
else ()
# Check with DEFINED as the found version may be 0.
if(DEFINED ${FPHSA_VERSION_VAR})
set(VERSION_MSG "(found version \"${${FPHSA_VERSION_VAR}}\")")
endif()
endif ()
if(VERSION_OK)
string(APPEND DETAILS "[v${${FPHSA_VERSION_VAR}}(${${_NAME}_FIND_VERSION})]")
else()
set(${_NAME}_FOUND FALSE)
endif()
# print the result:
if (${_NAME}_FOUND)
FIND_PACKAGE_MESSAGE(${_NAME} "Found ${_NAME}: ${${_FIRST_REQUIRED_VAR}} ${VERSION_MSG} ${COMPONENT_MSG}" "${DETAILS}")
else ()
if(FPHSA_CONFIG_MODE)
_FPHSA_HANDLE_FAILURE_CONFIG_MODE()
else()
if(NOT VERSION_OK)
_FPHSA_FAILURE_MESSAGE("${FPHSA_FAIL_MESSAGE}: ${VERSION_MSG} (found ${${_FIRST_REQUIRED_VAR}})")
else()
_FPHSA_FAILURE_MESSAGE("${FPHSA_FAIL_MESSAGE} (missing:${MISSING_VARS}) ${VERSION_MSG}")
endif()
endif()
endif ()
set(${_NAME}_FOUND ${${_NAME}_FOUND} PARENT_SCOPE)
set(${_NAME_UPPER}_FOUND ${${_NAME}_FOUND} PARENT_SCOPE)
endfunction()
leela-zero-0.17/cmake/Modules/FindPackageMessage.cmake 0000664 0000000 0000000 00000003034 13451323157 0022637 0 ustar 00root root 0000000 0000000 # Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.
#.rst:
# FindPackageMessage
# ------------------
#
#
#
# FIND_PACKAGE_MESSAGE( "message for user" "find result details")
#
# This macro is intended to be used in FindXXX.cmake modules files. It
# will print a message once for each unique find result. This is useful
# for telling the user where a package was found. The first argument
# specifies the name (XXX) of the package. The second argument
# specifies the message to display. The third argument lists details
# about the find result so that if they change the message will be
# displayed again. The macro also obeys the QUIET argument to the
# find_package command.
#
# Example:
#
# ::
#
# if(X11_FOUND)
# FIND_PACKAGE_MESSAGE(X11 "Found X11: ${X11_X11_LIB}"
# "[${X11_X11_LIB}][${X11_INCLUDE_DIR}]")
# else()
# ...
# endif()
function(FIND_PACKAGE_MESSAGE pkg msg details)
# Avoid printing a message repeatedly for the same find result.
if(NOT ${pkg}_FIND_QUIETLY)
string(REPLACE "\n" "" details "${details}")
set(DETAILS_VAR FIND_PACKAGE_MESSAGE_DETAILS_${pkg})
if(NOT "${details}" STREQUAL "${${DETAILS_VAR}}")
# The message has not yet been printed.
message(STATUS "${msg}")
# Save the find details in the cache to avoid printing the same
# message again.
set("${DETAILS_VAR}" "${details}"
CACHE INTERNAL "Details about finding ${pkg}")
endif()
endif()
endfunction()
leela-zero-0.17/cmake/Modules/GetGitRevisionDescription.cmake 0000664 0000000 0000000 00000011543 13451323157 0024310 0 ustar 00root root 0000000 0000000 # - Returns a version string from Git
#
# These functions force a re-configure on each git commit so that you can
# trust the values of the variables in your build system.
#
# get_git_head_revision( [ ...])
#
# Returns the refspec and sha hash of the current head revision
#
# git_describe( [ ...])
#
# Returns the results of git describe on the source tree, and adjusting
# the output so that it tests false if an error occurs.
#
# git_get_exact_tag( [ ...])
#
# Returns the results of git describe --exact-match on the source tree,
# and adjusting the output so that it tests false if there was no exact
# matching tag.
#
# git_local_changes()
#
# Returns either "CLEAN" or "DIRTY" with respect to uncommitted changes.
# Uses the return code of "git diff-index --quiet HEAD --".
# Does not regard untracked files.
#
# Requires CMake 2.6 or newer (uses the 'function' command)
#
# Original Author:
# 2009-2010 Ryan Pavlik
# http://academic.cleardefinition.com
# Iowa State University HCI Graduate Program/VRAC
#
# Copyright Iowa State University 2009-2010.
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
if(__get_git_revision_description)
return()
endif()
set(__get_git_revision_description YES)
# We must run the following at "include" time, not at function call time,
# to find the path to this module rather than the path to a calling list file
get_filename_component(_gitdescmoddir ${CMAKE_CURRENT_LIST_FILE} PATH)
function(get_git_head_revision _refspecvar _hashvar)
set(GIT_PARENT_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
set(GIT_DIR "${GIT_PARENT_DIR}/.git")
while(NOT EXISTS "${GIT_DIR}") # .git dir not found, search parent directories
set(GIT_PREVIOUS_PARENT "${GIT_PARENT_DIR}")
get_filename_component(GIT_PARENT_DIR ${GIT_PARENT_DIR} PATH)
if(GIT_PARENT_DIR STREQUAL GIT_PREVIOUS_PARENT)
# We have reached the root directory, we are not in git
set(${_refspecvar} "GITDIR-NOTFOUND" PARENT_SCOPE)
set(${_hashvar} "GITDIR-NOTFOUND" PARENT_SCOPE)
return()
endif()
set(GIT_DIR "${GIT_PARENT_DIR}/.git")
endwhile()
# check if this is a submodule
if(NOT IS_DIRECTORY ${GIT_DIR})
file(READ ${GIT_DIR} submodule)
string(REGEX REPLACE "gitdir: (.*)\n$" "\\1" GIT_DIR_RELATIVE ${submodule})
get_filename_component(SUBMODULE_DIR ${GIT_DIR} PATH)
get_filename_component(GIT_DIR ${SUBMODULE_DIR}/${GIT_DIR_RELATIVE} ABSOLUTE)
endif()
set(GIT_DATA "${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/git-data")
if(NOT EXISTS "${GIT_DATA}")
file(MAKE_DIRECTORY "${GIT_DATA}")
endif()
if(NOT EXISTS "${GIT_DIR}/HEAD")
return()
endif()
set(HEAD_FILE "${GIT_DATA}/HEAD")
configure_file("${GIT_DIR}/HEAD" "${HEAD_FILE}" COPYONLY)
configure_file("${_gitdescmoddir}/GetGitRevisionDescription.cmake.in"
"${GIT_DATA}/grabRef.cmake"
@ONLY)
include("${GIT_DATA}/grabRef.cmake")
set(${_refspecvar} "${HEAD_REF}" PARENT_SCOPE)
set(${_hashvar} "${HEAD_HASH}" PARENT_SCOPE)
endfunction()
function(git_describe _var)
if(NOT GIT_FOUND)
find_package(Git QUIET)
endif()
get_git_head_revision(refspec hash)
if(NOT GIT_FOUND)
set(${_var} "GIT-NOTFOUND" PARENT_SCOPE)
return()
endif()
if(NOT hash)
set(${_var} "HEAD-HASH-NOTFOUND" PARENT_SCOPE)
return()
endif()
# TODO sanitize
#if((${ARGN}" MATCHES "&&") OR
# (ARGN MATCHES "||") OR
# (ARGN MATCHES "\\;"))
# message("Please report the following error to the project!")
# message(FATAL_ERROR "Looks like someone's doing something nefarious with git_describe! Passed arguments ${ARGN}")
#endif()
#message(STATUS "Arguments to execute_process: ${ARGN}")
execute_process(COMMAND
"${GIT_EXECUTABLE}"
describe
${hash}
${ARGN}
WORKING_DIRECTORY
"${CMAKE_CURRENT_SOURCE_DIR}"
RESULT_VARIABLE
res
OUTPUT_VARIABLE
out
ERROR_QUIET
OUTPUT_STRIP_TRAILING_WHITESPACE)
if(NOT res EQUAL 0)
set(out "${out}-${res}-NOTFOUND")
endif()
set(${_var} "${out}" PARENT_SCOPE)
endfunction()
function(git_get_exact_tag _var)
git_describe(out --exact-match ${ARGN})
set(${_var} "${out}" PARENT_SCOPE)
endfunction()
function(git_local_changes _var)
if(NOT GIT_FOUND)
find_package(Git QUIET)
endif()
get_git_head_revision(refspec hash)
if(NOT GIT_FOUND)
set(${_var} "GIT-NOTFOUND" PARENT_SCOPE)
return()
endif()
if(NOT hash)
set(${_var} "HEAD-HASH-NOTFOUND" PARENT_SCOPE)
return()
endif()
execute_process(COMMAND
"${GIT_EXECUTABLE}"
diff-index --quiet HEAD --
WORKING_DIRECTORY
"${CMAKE_CURRENT_SOURCE_DIR}"
RESULT_VARIABLE
res
OUTPUT_VARIABLE
out
ERROR_QUIET
OUTPUT_STRIP_TRAILING_WHITESPACE)
if(res EQUAL 0)
set(${_var} "CLEAN" PARENT_SCOPE)
else()
set(${_var} "DIRTY" PARENT_SCOPE)
endif()
endfunction()
leela-zero-0.17/cmake/Modules/GetGitRevisionDescription.cmake.in 0000664 0000000 0000000 00000002403 13451323157 0024710 0 ustar 00root root 0000000 0000000 #
# Internal file for GetGitRevisionDescription.cmake
#
# Requires CMake 2.6 or newer (uses the 'function' command)
#
# Original Author:
# 2009-2010 Ryan Pavlik
# http://academic.cleardefinition.com
# Iowa State University HCI Graduate Program/VRAC
#
# Copyright Iowa State University 2009-2010.
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
set(HEAD_HASH)
file(READ "@HEAD_FILE@" HEAD_CONTENTS LIMIT 1024)
string(STRIP "${HEAD_CONTENTS}" HEAD_CONTENTS)
if(HEAD_CONTENTS MATCHES "ref")
# named branch
string(REPLACE "ref: " "" HEAD_REF "${HEAD_CONTENTS}")
if(EXISTS "@GIT_DIR@/${HEAD_REF}")
configure_file("@GIT_DIR@/${HEAD_REF}" "@GIT_DATA@/head-ref" COPYONLY)
else()
configure_file("@GIT_DIR@/packed-refs" "@GIT_DATA@/packed-refs" COPYONLY)
file(READ "@GIT_DATA@/packed-refs" PACKED_REFS)
if(${PACKED_REFS} MATCHES "([0-9a-z]*) ${HEAD_REF}")
set(HEAD_HASH "${CMAKE_MATCH_1}")
endif()
endif()
else()
# detached HEAD
configure_file("@GIT_DIR@/HEAD" "@GIT_DATA@/head-ref" COPYONLY)
endif()
if(NOT HEAD_HASH)
file(READ "@GIT_DATA@/head-ref" HEAD_HASH LIMIT 1024)
string(STRIP "${HEAD_HASH}" HEAD_HASH)
endif()
leela-zero-0.17/gtest/ 0000775 0000000 0000000 00000000000 13451323157 0014632 5 ustar 00root root 0000000 0000000 leela-zero-0.17/msvc/ 0000775 0000000 0000000 00000000000 13451323157 0014454 5 ustar 00root root 0000000 0000000 leela-zero-0.17/msvc/.gitignore 0000664 0000000 0000000 00000000071 13451323157 0016442 0 ustar 00root root 0000000 0000000 Debug
Release
packages
.orig
x64
.vs
*.db
*.opendb
*.user leela-zero-0.17/msvc/VS2015/ 0000775 0000000 0000000 00000000000 13451323157 0015314 5 ustar 00root root 0000000 0000000 leela-zero-0.17/msvc/VS2015/autogtp.vcxproj 0000664 0000000 0000000 00000037403 13451323157 0020423 0 ustar 00root root 0000000 0000000
Debugx64Releasex64falseDocumenttruecopy %(FullPath) $(OutputPath)$(OutputPath)curl.execopy %(FullPath) $(OutputPath)$(OutputPath)curl.exeDocumentcopy %(FullPath) $(OutputPath)$(OutputPath)gzip.execopy %(FullPath) $(OutputPath)$(OutputPath)gzip.exetruetruetruetruetruetruetruetrue"$(QTDIR)\bin\moc.exe" "%(FullPath)" -o "$(ConfigurationName)\moc_%(Filename).cpp" -D_CONSOLE -DUNICODE -D_UNICODE -DWIN32 -DWIN64 -DQT_DLL -DQT_NO_DEBUG -DQT_CORE_LIB -DNDEBUG "-I." "-I$(QTDIR)\include" "-I$(QTDIR)\include\QtCore" "-I.\release" "-I$(QTDIR)\mkspecs\win32-msvc"Moc%27ing Console.h..."$(QTDIR)\bin\moc.exe" "%(FullPath)" -o "$(ConfigurationName)\moc_%(Filename).cpp" -D_CONSOLE -DUNICODE -D_UNICODE -DWIN32 -DWIN64 -DQT_DLL -DQT_CORE_LIB "-I." "-I$(QTDIR)\include" "-I$(QTDIR)\include\QtCore" "-I.\debug" "-I$(QTDIR)\mkspecs\win32-msvc"Moc%27ing Console.h...$(ConfigurationName)\moc_%(Filename).cpp$(ConfigurationName)\moc_%(Filename).cpp$(QTDIR)\bin\moc.exe;%(FullPath)$(QTDIR)\bin\moc.exe;%(FullPath)"$(QTDIR)\bin\moc.exe" "%(FullPath)" -o "$(ConfigurationName)\moc_%(Filename).cpp" -D_CONSOLE -DUNICODE -D_UNICODE -DWIN32 -DWIN64 -DQT_DLL -DQT_NO_DEBUG -DQT_CORE_LIB -DNDEBUG "-I." "-I$(QTDIR)\include" "-I$(QTDIR)\include\QtCore" "-I.\release" "-I$(QTDIR)\mkspecs\win32-msvc"Moc%27ing Job.h..."$(QTDIR)\bin\moc.exe" "%(FullPath)" -o "$(ConfigurationName)\moc_%(Filename).cpp" -D_CONSOLE -DUNICODE -D_UNICODE -DWIN32 -DWIN64 -DQT_DLL -DQT_CORE_LIB "-I." "-I$(QTDIR)\include" "-I$(QTDIR)\include\QtCore" "-I.\debug" "-I$(QTDIR)\mkspecs\win32-msvc"Moc%27ing Job.h...$(ConfigurationName)\moc_%(Filename).cpp$(ConfigurationName)\moc_%(Filename).cpp$(QTDIR)\bin\moc.exe;%(FullPath)$(QTDIR)\bin\moc.exe;%(FullPath)"$(QTDIR)\bin\moc.exe" "%(FullPath)" -o "$(ConfigurationName)\moc_%(Filename).cpp" -D_CONSOLE -DUNICODE -D_UNICODE -DWIN32 -DWIN64 -DQT_DLL -DQT_NO_DEBUG -DQT_CORE_LIB -DNDEBUG "-I." "-I$(QTDIR)\include" "-I$(QTDIR)\include\QtCore" "-I.\release" "-I$(QTDIR)\mkspecs\win32-msvc"Moc%27ing Management.h..."$(QTDIR)\bin\moc.exe" "%(FullPath)" -o "$(ConfigurationName)\moc_%(Filename).cpp" -D_CONSOLE -DUNICODE -D_UNICODE -DWIN32 -DWIN64 -DQT_DLL -DQT_CORE_LIB "-I." "-I$(QTDIR)\include" "-I$(QTDIR)\include\QtCore" "-I.\debug" "-I$(QTDIR)\mkspecs\win32-msvc"Moc%27ing Management.h...$(ConfigurationName)\moc_%(Filename).cpp$(ConfigurationName)\moc_%(Filename).cpp$(QTDIR)\bin\moc.exe;%(FullPath)$(QTDIR)\bin\moc.exe;%(FullPath)"$(QTDIR)\bin\moc.exe" "%(FullPath)" -o "$(ConfigurationName)\moc_%(Filename).cpp" -D_CONSOLE -DUNICODE -D_UNICODE -DWIN32 -DWIN64 -DQT_DLL -DQT_NO_DEBUG -DQT_CORE_LIB -DNDEBUG "-I." "-I$(QTDIR)\include" "-I$(QTDIR)\include\QtCore" "-I.\release" "-I$(QTDIR)\mkspecs\win32-msvc"Moc%27ing Worker.h..."$(QTDIR)\bin\moc.exe" "%(FullPath)" -o "$(ConfigurationName)\moc_%(Filename).cpp" -D_CONSOLE -DUNICODE -D_UNICODE -DWIN32 -DWIN64 -DQT_DLL -DQT_CORE_LIB "-I." "-I$(QTDIR)\include" "-I$(QTDIR)\include\QtCore" "-I.\debug" "-I$(QTDIR)\mkspecs\win32-msvc"Moc%27ing Worker.h...$(ConfigurationName)\moc_%(Filename).cpp$(ConfigurationName)\moc_%(Filename).cpp$(QTDIR)\bin\moc.exe;%(FullPath)$(QTDIR)\bin\moc.exe;%(FullPath)Documenttrue$(QTDIR)\mkspecs\features\data\dummy.cpp;%(AdditionalInputs)cl -Bx"$(QTDIR)\bin\qmake.exe" -nologo -Zc:wchar_t -FS -Zc:rvalueCast -Zc:inline -Zc:strictStrings -Zc:throwingNew -Zc:referenceBinding -Zi -MDd -W3 -w34100 -w34189 -w44996 -w44456 -w44457 -w44458 -wd4577 -wd4467 -E $(QTDIR)\mkspecs\features\data\dummy.cpp 2>NUL >debug\moc_predefs.hGenerate moc_predefs.hdebug\moc_predefs.h;%(Outputs)Document$(QTDIR)\mkspecs\features\data\dummy.cpp;%(AdditionalInputs)cl -Bx"$(QTDIR)\bin\qmake.exe" -nologo -Zc:wchar_t -FS -Zc:rvalueCast -Zc:inline -Zc:strictStrings -Zc:throwingNew -Zc:referenceBinding -O2 -MD -W3 -w34100 -w34189 -w44996 -w44456 -w44457 -w44458 -wd4577 -wd4467 -E $(QTDIR)\mkspecs\features\data\dummy.cpp 2>NUL >release\moc_predefs.hGenerate moc_predefs.hrelease\moc_predefs.h;%(Outputs)true{B12702AD-ABFB-343A-A199-8E24837244A3}Qt4VSv1.010.0.16299.0Applicationv140Applicationv140$(SolutionDir)$(Platform)\$(Configuration)\$(SolutionDir)$(Platform)\$(Configuration)\$(Platform)\$(Configuration)\autogtp\UNICODE;_UNICODE;WIN32;WIN64;QT_CORE_LIB;%(PreprocessorDefinitions)DisabledProgramDatabaseMultiThreadedDebugDLL.;$(QTDIR)\include;.\GeneratedFiles\$(ConfigurationName);$(QTDIR)\include\QtCore;%(AdditionalIncludeDirectories)trueConsole$(OutDir)\$(ProjectName).exe$(QTDIR)\lib;%(AdditionalLibraryDirectories)trueqtmaind.lib;Qt5Cored.lib;%(AdditionalDependencies)UseLinkTimeCodeGenerationUNICODE;_UNICODE;WIN32;WIN64;QT_NO_DEBUG;NDEBUG;QT_CORE_LIB;%(PreprocessorDefinitions)MultiThreadedDLL.;$(QTDIR)\include;.\GeneratedFiles\$(ConfigurationName);$(QTDIR)\include\QtCore;%(AdditionalIncludeDirectories)trueConsole$(OutDir)\$(ProjectName).exe$(QTDIR)\lib;%(AdditionalLibraryDirectories)falseqtmain.lib;Qt5Core.lib;%(AdditionalDependencies)UseLinkTimeCodeGeneration