Skip to content

Commit

Permalink
Devel (#1949)
Browse files Browse the repository at this point in the history
* tests/autodiff: Add expected results to test_atomizer_specs

Python only, the compiled implementation is broken.

Signed-off-by: Jan Vesely <[email protected]>

* llvm/builtins: Drop vec_copy

Unused. Untested.

Signed-off-by: Jan Vesely <[email protected]>

* tests/llvm/intrinics: Drop temporary variables with results

Signed-off-by: Jan Vesely <[email protected]>

* llvm: Convert coth, csch, and tanh to builtin functions

Signed-off-by: Jan Vesely <[email protected]>

* llvm/tests/builtins: Add tanh, coth, and csch tests

Includes benchmark.

Signed-off-by: Jan Vesely <[email protected]>

* llvm, mechanisms/DDM: Use helpers.fneg instead of opencoding it

Signed-off-by: Jan Vesely <[email protected]>

* llvm, functions/DDI: Use helpers.fneg instead of opencoding it

Signed-off-by: Jan Vesely <[email protected]>

* llvm, functions/Distance: Call fabs builtin instead of opencoding it

Signed-off-by: Jan Vesely <[email protected]>

* llvm/helpers: Convert 'is_close' to builtin function

Use fabs builtins instead of opencoding them.

Signed-off-by: Jan Vesely <[email protected]>

* llvm, tests/builtins: Remove lcoal import of pycuda

Signed-off-by: Jan Vesely <[email protected]>

* tests/llvm/builtins_matrix: Consolidate 'dot' tests

Signed-off-by: Jan Vesely <[email protected]>

* github-actions: Restrict tests to 80 mins

Signed-off-by: Jan Vesely <[email protected]>

* dependabot: Allow up to 15 open pull requests for pip packages

Signed-off-by: Jan Vesely <[email protected]>

* treewide: Rename Composition argument: 'bin_execute' -> 'execution_mode' (#1924)

Signed-off-by: Jan Vesely <[email protected]>

* teewide: Don't use 'np.float'

Deprecated in numpy 1.20

Signed-off-by: Jan Vesely <[email protected]>

* llvm, composition: Preserve CompExecution instances across runs and executions

GPU execution already did this, extend the approach to CPU execution.
Signed-off-by: Jan Vesely <[email protected]>

* llvm/execution: Move struct generators closer together

Signed-off-by: Jan Vesely <[email protected]>

* llvm/execution: Store binary buffer of scheduler structures locally

Signed-off-by: Jan Vesely <[email protected]>

* llvm/execution: Store binary structures of state,params, and data locally

Signed-off-by: Jan Vesely <[email protected]>

* llvm/execution: Consolidate debug_flag location to a new parent class

Signed-off-by: Jan Vesely <[email protected]>

* llvm/execution: Move _get_compilation_param to the shared ancestor

This will be used by the Mech/FuncExecution.
Signed-off-by: Jan Vesely <[email protected]>

* llvm/execution: Store binary structures for function/mechanism param and state locally

Signed-off-by: Jan Vesely <[email protected]>

* llvm/execution: Deduplicate conversion of function variable

Signed-off-by: Jan Vesely <[email protected]>

* llvm/execution: Fix misleading comment

Do not list 7 names for 6 parameters
Signed-off-by: Jan Vesely <[email protected]>

* llvm/execution: Use attribute names instead of object types when syncing back parameter values

Improves autodiff benchmarks by 3-5%.
Signed-off-by: Jan Vesely <[email protected]>

* tests/composition: Run all compiled modes in the recurrent transfer mechanism test

Signed-off-by: Jan Vesely <[email protected]>

* tests/builtins_random: Drop misleading comment

Signed-off-by: Jan Vesely <[email protected]>

* llvm/execution: Use correct type to print scheduler conditions structure stats

Add 'stat' to the test of debugging flags.

Fixes: fd5a419 ("llvm/execution: Store binary buffer of scheduler structures locally")
Signed-off-by: Jan Vesely <[email protected]>

* tests: Use a new 'func_mode' fixture to parametrize function tests

The fixture automatically parametrizes tests using 'Python', 'LLVM', and 'PTX' values.
Testing:
pytest --co > tests.out
Before and after the change is the same (other than the collection
time).

Signed-off-by: Jan Vesely <[email protected]>

* tests: Use a new 'mech_mode' fixture to parametrize mechanism tests

The fixture automatically parametrizes tests using 'Python', 'LLVM', and 'PTX' values.
Testing:
pytest --co > tests.out
Before and after the change is the same (other than the collection time).

Signed-off-by: Jan Vesely <[email protected]>

* llvm, tests/mechanisms: Enable partial LLVM/PTX tests for integration_rate_0_8_initial_0_5

Signed-off-by: Jan Vesely <[email protected]>

* llvm, tests/control_mechanism: Remove unsupported per-node PTX execution mode

Fixes: 5c5d747 ("llvm/cuda: Drop
references to per node PTX execution")
Signed-off-by: Jan Vesely <[email protected]>

* tests: Use a new 'comp_mode' fixture to parametrize composition tests

The fixture automatically parametrizes the test using 'Python', 'LLVM',
'LLVMExec', 'LLVMRun', 'PTXExec', and 'PTXRun' values.

Testing:
pytest --co > tests.out
The only changes are slight reordering of tests and parameters,
execution mode is put in the first place for
'test_run_composition_vector' and 'test_ddm_is_finished'.

Signed-off-by: Jan Vesely <[email protected]>

* llvm, tests/composition/control: Enable PTX variants of more tests

test_multilevel_control
test_recurrent_control
test_grid_search_random_selection
test_input_CIM_assignment

Signed-off-by: Jan Vesely <[email protected]>

* tests/mechanism: Add explanatory comments to tests that need compiled scheduler

Signed-off-by: Jan Vesely <[email protected]>

* tests/RecurrentTransferMechanism: Simplify parameter ids

Signed-off-by: Jan Vesely <[email protected]>

* tests/composition: Clarify comment in AAB_integrator test

Signed-off-by: Jan Vesely <[email protected]>

* tests: Use pytest helper to generate super sets of composition execution modes

Signed-off-by: Jan Vesely <[email protected]>

* tests/llvm/builtins_matrix: Add PTX variants of hadamard and scalar tests

Signed-off-by: Jan Vesely <[email protected]>

* tests/llvm/builtins_vector: Add PTX variants of all vector tests

Signed-off-by: Jan Vesely <[email protected]>

* tests/composition: Remove duplicate run input generator tests

The exact same tests are in TestRunInputSpecifications.
Signed-off-by: Jan Vesely <[email protected]>

* llvm/cuda, tests/composition: Add PTXRun variant of the fallback test

Fix PTXExec marks.
Signed-off-by: Jan Vesely <[email protected]>

* tests: Use a new 'autodif_mode' fixture to parametrize composition tests

The fixture automatically parametrizes tests using 'Python' and
'LLVMRun' values.
The following tests are now enabled and skipped at runtime:
test_pytorch_loss_spec[LLVMRun]
test_params_stay_separate[LLVMRun]
test_xor_nested_no_train_then_train[LLVMRun-400-4-10-1e-05]

Signed-off-by: Jan Vesely <[email protected]>

* tests/integrator_mechanism: Rename 'mode' -> 'mech_mode' for consistency

Signed-off-by: Jan Vesely <[email protected]>

* tests/control_mechanism: Drop redundant 'mode' parameter

Signed-off-by: Jan Vesely <[email protected]>

* Buffer: do not replace initializer of 0s with default

* LeabraFunction: make training_flag dependent on network

* llvm, components/OutputPort: Use cost function of the port function instead of port's FunctionParam

Signed-off-by: Jan Vesely <[email protected]>

* llvm, AutodiffComposition: Use matrices of projection functions instead projections' alias

Signed-off-by: Jan Vesely <[email protected]>

* llvm, component: Do not include SharedParameters in compiled structures

Values of SharedParameters are already stored elsewhere.
Signed-off-by: Jan Vesely <[email protected]>

* llvm, composition: Replace execution_mode string with enum.Flags

Signed-off-by: Jan Vesely <[email protected]>

* fix: monkey patch rich.console._is_jupyter for colab

* Fixed the patch

* Codestyle fixes and better documentation

* requirements: Restrict rich to <9.13

Signed-off-by: Jan Vesely <[email protected]>

* fix(Parameter): setting value of Parameter to a method

code intended to ensure Components whose methods are set as a Parameter
value after intiialization are marked for context initialization would mark any
object, which could cause crashes

* refac(utilities): exclude bool and enum from is_numeric

* fix(utilities): copy_iterable_with_shared: failure for defaultdict

* fix(utilities): numpy DeprecationWarning casting np.integer to float

convert_all_elements_to_np_array: cast and pass through non-ragged arrays

* fix(utilities): numpy array_equals DeprecationWarning for embedded arrays

* tests: Add fixture for compiled composition tests that don't support per-node compilation

This changes the order of generated tests slightly.
Signed-off-by: Jan Vesely <[email protected]>

* Component: make dot-notation base use get instead of _get

* Component: only call _update_default_variable on Components

* BayesGLM: fix attribute typo in error messages

* IntegratorFunction: sort parameter names for incorrect length error

* Feat/pnl progress (#1938)

* • composition.py
  - run():  use rich.Progress for looping through trials

* -

* -

* -

* -

* -

* -

* -

* -

* -

* -

* -

* • composition.py
  - import placed at top

* -

* • composition.py
  - run(): added support for indeterminate progress using rich

* • composition.py
  - run(): clean-up of rich.progress code

* • composition.py
  - run(): clean-up of rich.progress code

* -

* • composition.py
  - run(): added support for indeterminate progress using rich

* • composition.py
  - run(): simulation progress now working properly

* • composition.py
  - run(): added show_progress and show_output args
  - execute(): added show_output arg

* • composition.py
  - run(): modified example in controlsignal.py docstring to pass test

* • composition.py
  - run(): modified example in controlsignal.py docstring to pass test

* -

* • Pulled from current devel

* • composition.py: bug fixes

* -

* • composition.py
  - last commit before implementing PNLprogress

* • composition.py
  - first draft using PNLProgress and _report_output

* • composition.py
  - first draft using PNLProgress and _report_output

* -

* -

* -

* -

* • PNLProgress working

* -

* • PNLProgress:  elaborated for future support of pnl_view

* -

* • progress.py:  added support for showing simulations

* • progress.py:  added support for showing simulations

* -

* -

* -

* • Fixed bug causing crash in test_nested_composition_run

* • Fixed bug causing crash in test_nested_composition_run

* -

* • Codestyle fixes

* • progress.py:
  - fixed simulation progress reporting
  - should consolidate all executions in a given simualation to a single task

• composition.py:
  - limited progress reporting to execute()
    (no longer in run)

• autodiffcomposition.py:
  - execute: added progress reporting
  - still need to handle output report

* -

* -

* -

* • Merged with devel

* -

* • Merged with devel

* -

* -

* -

* -

* -

* -

* • progress.py: working for nested sims

* -

* -

* -

* -

* -

* • composition.py: docstring updated for output and progress reporting

* • progress.py - bug fix
• composition.py - change show_output default to False

* • progress.py - bug fix

* • progress.py - patch trial_num reporting bug (with hack)

* • progress.py: before switch from rich_report to full_report

* -

* -

* -

* • Progress: before modifying PNLProgers._use_rich

* • Progress: implemented CAPTURE option for rich output

* -

* -

* • Preferences.rst - pointed to PreferenceSet.py
• preferenceset.py - created docstring to describe Standard Preferences

* -

* -

Co-authored-by: jdcpni <pniintel55>

* llvm/execution/cuda: Inline '_get_ctype_bytes' into its only caller

Disallow empty structures. This used to be the case for functions
without any state. Every component has at least 'execution_count' in its
state.

Signed-off-by: Jan Vesely <[email protected]>

* llvm/execution/cuda: Use numpy full to generate the number of runs

Signed-off-by: Jan Vesely <[email protected]>

* llvm/execution/cuda: Simplify generation of evaluation input buffer

Signed-off-by: Jan Vesely <[email protected]>

* llvm, functions/GridSearch: Change select_min signature to use <start, stop) instead of count parameter

Signed-off-by: Jan Vesely <[email protected]>

* llvm/cuda: Don't reuse allocations array from cuda_evauate

It's going away
Signed-off-by: Jan Vesely <[email protected]>

* llvm, mechanism/OptimizationControl: Add wrapper function to iterate over multiple evaluations.

Evaluated sample is generated within the loop.
This removes the need to prepopulate an array of possible evaluations.
Signed-off-by: Jan Vesely <[email protected]>

* llvm/cuda: Use locally generated samples in GPU evaluate

Avoid generating allocation array in Python before invoking the GPU kernel.
Signed-off-by: Jan Vesely <[email protected]>

drop itertools

* llvm, mechanisms/OptimizationControl: Move allocation generation to helpers

Signed-off-by: Jan Vesely <[email protected]>

* llvm, functions/GridSearch: Generate allocation samples locally if not provided

Signed-off-by: Jan Vesely <[email protected]>

* llvm, functions/GridSearch: Update the best value of the best allocation only once

The allocation value is not used in the search loop,
so it can be updated at the end after the index of the selected results
is known.
This avoids generating multiple allocation samples if they're not
provided.
Signed-off-by: Jan Vesely <[email protected]>

* llvm, functions/GridSearch: Rename '_get_optimized_composition' -> '_get_optimized_controller'

The function returns and instance of optimization control mechanism.
Signed-off-by: Jan Vesely <[email protected]>

* llvm/execution, functions/GridSearch: Implement multithreaded parallel evaluate

Signed-off-by: Jan Vesely <[email protected]>

* Refactor/pnl report (#1942)

* • composition.py
  - run():  use rich.Progress for looping through trials

* -

* -

* -

* -

* -

* -

* -

* -

* -

* -

* -

* • composition.py
  - import placed at top

* -

* • composition.py
  - run(): added support for indeterminate progress using rich

* • composition.py
  - run(): clean-up of rich.progress code

* • composition.py
  - run(): clean-up of rich.progress code

* -

* • composition.py
  - run(): added support for indeterminate progress using rich

* • composition.py
  - run(): simulation progress now working properly

* • composition.py
  - run(): added show_progress and show_output args
  - execute(): added show_output arg

* • composition.py
  - run(): modified example in controlsignal.py docstring to pass test

* • composition.py
  - run(): modified example in controlsignal.py docstring to pass test

* -

* • Pulled from current devel

* • composition.py: bug fixes

* -

* • composition.py
  - last commit before implementing PNLprogress

* • composition.py
  - first draft using PNLProgress and _report_output

* • composition.py
  - first draft using PNLProgress and _report_output

* -

* -

* -

* -

* • PNLProgress working

* -

* • PNLProgress:  elaborated for future support of pnl_view

* -

* • progress.py:  added support for showing simulations

* • progress.py:  added support for showing simulations

* -

* -

* -

* • Fixed bug causing crash in test_nested_composition_run

* • Fixed bug causing crash in test_nested_composition_run

* -

* • Codestyle fixes

* • progress.py:
  - fixed simulation progress reporting
  - should consolidate all executions in a given simualation to a single task

• composition.py:
  - limited progress reporting to execute()
    (no longer in run)

• autodiffcomposition.py:
  - execute: added progress reporting
  - still need to handle output report

* -

* -

* -

* • Merged with devel

* -

* • Merged with devel

* -

* -

* -

* -

* -

* -

* • progress.py: working for nested sims

* -

* -

* -

* -

* -

* • composition.py: docstring updated for output and progress reporting

* • progress.py - bug fix
• composition.py - change show_output default to False

* • progress.py - bug fix

* • progress.py - patch trial_num reporting bug (with hack)

* • progress.py: before switch from rich_report to full_report

* -

* -

* -

* • Progress: before modifying PNLProgers._use_rich

* • Progress: implemented CAPTURE option for rich output

* -

* -

* • Preferences.rst - pointed to PreferenceSet.py
• preferenceset.py - created docstring to describe Standard Preferences

* -

* -

* • tests
  - composition:  added test_progress.py with unit tests for PNLProgress
• composition.py
  - execute(): modified context passed to node if it is a mechanism
               (assigns context.source as ContextFlags.COMPOSITION)

* -

* • composition.py and progress.py:
  refactoring show_output and show_progress into: report_output, report_progress, report_simulations, report_to_devices

* -

* -

* • report.py: updated docstrings with new args/attrs

* • report.py:
  - refactored args to use "report" as root
  - added _use_rich_console and _use_rich_capture
  - TODO: allow independent controle of consolse and capture

* • test_report.py: updated to use report_progress and report_to_devices

* -

* • report.py:
  - added independent rich divert and report recording

* -

* -

* -

* -

* -

* -

* -

* -

Co-authored-by: jdcpni <pniintel55>

* bug(Report): add undefined imports

* tests: reporting: add reportOutputPref output tests

* Preferences: allow skipping validation

prior to 8c0eecc, any value for
reportOutputPref would pass Preference validation due to an
iscompatible check of its reference setting (bool).
0f78ef3 allows reportOutputPref to take a str
as well. Since there is no obvious non-workaround way to allow a str/bool value
in the current validation, this commit allows passing of skip_validation=True to
PreferenceSet.set_preference to mimic the old behavior and reenable the str/bool
setting

* Component: don't store self in parameter_components

some Components have a parameter value of one of its methods, which will get
parsed back to itself

* Fix/report/sims (#1948)

* • composition.py
  - run():  use rich.Progress for looping through trials

* -

* -

* -

* -

* -

* -

* -

* -

* -

* -

* -

* • composition.py
  - import placed at top

* -

* • composition.py
  - run(): added support for indeterminate progress using rich

* • composition.py
  - run(): clean-up of rich.progress code

* • composition.py
  - run(): clean-up of rich.progress code

* -

* • composition.py
  - run(): added support for indeterminate progress using rich

* • composition.py
  - run(): simulation progress now working properly

* • composition.py
  - run(): added show_progress and show_output args
  - execute(): added show_output arg

* • composition.py
  - run(): modified example in controlsignal.py docstring to pass test

* • composition.py
  - run(): modified example in controlsignal.py docstring to pass test

* -

* • Pulled from current devel

* • composition.py: bug fixes

* -

* • composition.py
  - last commit before implementing PNLprogress

* • composition.py
  - first draft using PNLProgress and _report_output

* • composition.py
  - first draft using PNLProgress and _report_output

* -

* -

* -

* -

* • PNLProgress working

* -

* • PNLProgress:  elaborated for future support of pnl_view

* -

* • progress.py:  added support for showing simulations

* • progress.py:  added support for showing simulations

* -

* -

* -

* • Fixed bug causing crash in test_nested_composition_run

* • Fixed bug causing crash in test_nested_composition_run

* -

* • Codestyle fixes

* • progress.py:
  - fixed simulation progress reporting
  - should consolidate all executions in a given simualation to a single task

• composition.py:
  - limited progress reporting to execute()
    (no longer in run)

• autodiffcomposition.py:
  - execute: added progress reporting
  - still need to handle output report

* -

* -

* -

* • Merged with devel

* -

* • Merged with devel

* -

* -

* -

* -

* -

* -

* • progress.py: working for nested sims

* -

* -

* -

* -

* -

* • composition.py: docstring updated for output and progress reporting

* • progress.py - bug fix
• composition.py - change show_output default to False

* • progress.py - bug fix

* • progress.py - patch trial_num reporting bug (with hack)

* • progress.py: before switch from rich_report to full_report

* -

* -

* -

* • Progress: before modifying PNLProgers._use_rich

* • Progress: implemented CAPTURE option for rich output

* -

* -

* • Preferences.rst - pointed to PreferenceSet.py
• preferenceset.py - created docstring to describe Standard Preferences

* -

* -

* • tests
  - composition:  added test_progress.py with unit tests for PNLProgress
• composition.py
  - execute(): modified context passed to node if it is a mechanism
               (assigns context.source as ContextFlags.COMPOSITION)

* -

* • composition.py and progress.py:
  refactoring show_output and show_progress into: report_output, report_progress, report_simulations, report_to_devices

* -

* -

* • report.py: updated docstrings with new args/attrs

* • report.py:
  - refactored args to use "report" as root
  - added _use_rich_console and _use_rich_capture
  - TODO: allow independent controle of consolse and capture

* • test_report.py: updated to use report_progress and report_to_devices

* -

* • report.py:
  - added independent rich divert and report recording

* -

* -

* -

* -

* -

* -

* -

* -

* -

* • report.py
  - report_output: fixes for simulation reporting

* -

* • composition.py
  - evaluate(): added use of Report context in call to composition.run()

* -

* -

* -

* -

* -

* -

* • report.py: docstring added

* -

* -

* -

* -

* • report.py:  modify to use ReportOutput enum

* -

* -

* • report.py: refactored to use ReportOutput enum

* • report.py: refactored to use ReportDevices enum

* • Project: refactored to use ReportOutput and ReportDevices enums
• Component:
  reportOoutputPref property and setter:  enforce assigment and retrieval of ReportOutput

* • Project: refactored to use ReportProgress and ReportSimulations enums

* -

* -

* • basepreferenceset.py:
  - modified reportOutputPref handling to convert False to ReportOutput.OFF and True to ReportOutput.TERSE

* -

* • report.py: allow reportOutputPrefs to be a list that includes 'params' and a ReportOutput option

* -

* -

* -

Co-authored-by: jdcpni <pniintel55>

Co-authored-by: Jan Vesely <[email protected]>
Co-authored-by: Jan Vesely <[email protected]>
Co-authored-by: David Turner <[email protected]>
Co-authored-by: jdcpni <[email protected]>
  • Loading branch information
5 people authored Mar 12, 2021
1 parent aabefef commit a2d06bf
Show file tree
Hide file tree
Showing 85 changed files with 3,779 additions and 3,023 deletions.
1 change: 1 addition & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,4 @@ updates:
prefix: "requirements"
labels:
- "deps"
open-pull-requests-limit: 15
1 change: 1 addition & 0 deletions .github/workflows/pnl-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ jobs:
flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
- name: Test with pytest
timeout-minutes: 80
run: pytest --junit-xml=tests_out.xml --verbosity=0 -n auto --maxprocesses=2

- name: Upload test results
Expand Down
43 changes: 43 additions & 0 deletions conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,31 @@ def pytest_runtest_setup(item):

doctest.ELLIPSIS_MARKER = "[...]"

def pytest_generate_tests(metafunc):
mech_and_func_modes = ['Python',
pytest.param('LLVM', marks=pytest.mark.llvm),
pytest.param('PTX', marks=[pytest.mark.llvm,
pytest.mark.cuda])
]

if "func_mode" in metafunc.fixturenames:
metafunc.parametrize("func_mode", mech_and_func_modes)

if "mech_mode" in metafunc.fixturenames:
metafunc.parametrize("mech_mode", mech_and_func_modes)

if "comp_mode_no_llvm" in metafunc.fixturenames:
modes = [m for m in get_comp_execution_modes()
if m.values[0] is not pnlvm.ExecutionMode.LLVM]
metafunc.parametrize("comp_mode", modes)

elif "comp_mode" in metafunc.fixturenames:
metafunc.parametrize("comp_mode", get_comp_execution_modes())

if "autodiff_mode" in metafunc.fixturenames:
auto_modes = [pnlvm.ExecutionMode.Python,
pytest.param(pnlvm.ExecutionMode.LLVMRun, marks=pytest.mark.llvm)]
metafunc.parametrize("autodiff_mode", auto_modes)

def pytest_runtest_call(item):
# seed = int(item.config.getoption('--pnl-seed'))
Expand All @@ -65,6 +90,24 @@ def pytest_runtest_teardown(item):

pnlvm.cleanup()

@pytest.fixture
def comp_mode_no_llvm():
# dummy fixture to allow 'comp_mode' filtering
pass

@pytest.helpers.register
def get_comp_execution_modes():
return [pytest.param(pnlvm.ExecutionMode.Python),
pytest.param(pnlvm.ExecutionMode.LLVM, marks=pytest.mark.llvm),
pytest.param(pnlvm.ExecutionMode.LLVMExec, marks=pytest.mark.llvm),
pytest.param(pnlvm.ExecutionMode.LLVMRun, marks=pytest.mark.llvm),
pytest.param(pnlvm.ExecutionMode.PTXExec, marks=[pytest.mark.llvm, pytest.mark.cuda]),
pytest.param(pnlvm.ExecutionMode.PTXRun, marks=[pytest.mark.llvm, pytest.mark.cuda])
]

@pytest.helpers.register
def cuda_param(val):
return pytest.param(val, marks=[pytest.mark.llvm, pytest.mark.cuda])

@pytest.helpers.register
def expand_np_ndarray(arr):
Expand Down
12 changes: 6 additions & 6 deletions docs/source/Compilation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,12 @@ Use

Compiled form of a model can be invoked by passing one of the following values to the `bin_execute` parameter of `Composition.run`, or `Composition.exec`:

* `False` or `Python`: Normal python execution
* `LLVM`: Compile and execute individual nodes. The scheduling loop still runs in Python. If any of the nodes fails to compile, an error is raised. *NOTE:* Schedules that require access to node data will not work correctly.
* `LLVMExec`: Execution of `Composition.exec` is replaced by a compiled equivalent. If the `Composition` fails to compile, an error is raised.
* `LLVMRun`: Execution of `Composition.run` is replaced by a compiled equivalent. If the `Composition` fails to compiler, an error is raised.
* `True`: This option attempts all three above mentioned granularities, and gracefully falls back to lower granularity. Warnings are raised in place of errors. This is the recommended way to invoke compiled execution as the final fallback is the Python baseline.
* `ExecutionMode.Python`: Normal python execution
* `ExecutionMode.LLVM`: Compile and execute individual nodes. The scheduling loop still runs in Python. If any of the nodes fails to compile, an error is raised. *NOTE:* Schedules that require access to node data will not work correctly.
* `ExecutionMode.LLVMExec`: Execution of `Composition.exec` is replaced by a compiled equivalent. If the `Composition` fails to compile, an error is raised.
* `ExecutionMode.LLVMRun`: Execution of `Composition.run` is replaced by a compiled equivalent. If the `Composition` fails to compile, an error is raised.
* `ExecutionMode.Auto`: This option attempts all three above mentioned granularities, and gracefully falls back to lower granularity. Warnings are raised in place of errors. This is the recommended way to invoke compiled execution as the final fallback is the Python baseline.

Note that data other than `Composition.run` outputs are not synchronized between Python and compiled execution.

It is possible to invoke compiled version of `FUnction` s and `Mechanism` s. This functionality is provided for testing purposes only, because of the lack of data synchronization it is not recommended for general use.
It is possible to invoke compiled version of `Function` s and `Mechanism` s. This functionality is provided for testing purposes only, because of the lack of data synchronization it is not recommended for general use.
1 change: 1 addition & 0 deletions docs/source/Composition.rst
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ Composition
Pathway
Scheduling
Visualization
Report

.. automodule:: psyneulink.core.compositions.composition
:members: Composition, NodeRole
Expand Down
1 change: 1 addition & 0 deletions docs/source/Core.rst
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,6 @@ Core
- `Visualization`
- `Scheduling`
- `Compilation`
- `Report`
- `Log`
- `json`
24 changes: 2 additions & 22 deletions docs/source/Preferences.rst
Original file line number Diff line number Diff line change
@@ -1,26 +1,6 @@
Preferences
===========

Standard prefereces:

- verbose (bool): enables/disables reporting of (non-exception) warnings and system function

- paramValidation (bool): enables/disables run-time validation of the execute method of a Function object

- reportOutput ([bool, str]): enables/disables reporting execution of `Component`\'s `execute <Component_Execution>`
method to console:
- ``True``: prints record of execution, including the input and output of the Component;
- 'params' or 'parameters': includes report of the Component's `parameter <Parameters>` values.
- 'terse': (Composition only) restricts output to just a listing of `trials <TimeScale.TRIAL>`, `time_steps
<TimeScale.TIME_STEP>` and `nodes <Composition_Nodes>` executed.

- log (bool): sets LogCondition for a given Component

- functionRunTimeParams (Modulation): uses run-time params to modulate execute method params

[ADDITIONAL DOCUMENTATION COMING...]


.. .. automodule:: psyneulink.core.globals.preferences
.. automodule:: psyneulink.core.globals.preferences.preferenceset
:members:
:exclude-members: Parameters, PreferenceLevel, PreferenceSetError, PreferenceEntry, PreferenceSetRegistry
:exclude-members: PreferenceSet, Parameters, PreferenceLevel, PreferenceSetError, PreferenceEntry, PreferenceSetRegistry
6 changes: 6 additions & 0 deletions docs/source/Report.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
Reporting
=========

.. automodule:: psyneulink.core.compositions.report
:members:
:exclude-members: ReportError, ProgressReport, Report
28 changes: 26 additions & 2 deletions psyneulink/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@

import numpy as _numpy

# We need to import rich here so we can monkey patch console._is_jupyter to work on
# google colab. This fix to rich is up as a pull request. See:
# https://github.com/willmcgugan/rich/pull/1085
# If accepted then this import and the monkey patch below can be removed.
import rich.console

# starred imports to allow user imports from top level
from . import core
from . import library
Expand All @@ -31,8 +37,26 @@
from .core import *
from .library import *

# from rich import print, box
# print("Initializing...")

# Monkey patch rich
def _is_jupyter() -> bool: # pragma: no cover
"""Check if we're running in a Jupyter notebook."""
try:
get_ipython # type: ignore
except NameError:
return False
shell = get_ipython().__class__.__name__ # type: ignore
full_class = str(get_ipython().__class__) # type: ignore
if shell == "ZMQInteractiveShell":
return True # Jupyter notebook or qtconsole
elif shell == "TerminalInteractiveShell":
return False # Terminal running IPython
elif "google.colab" in full_class: # IPython in Google Colab
return True
else:
return False # Other type (?)
rich.console._is_jupyter = _is_jupyter


_pnl_global_names = [
'primary_registries', 'System', 'Process'
Expand Down
45 changes: 28 additions & 17 deletions psyneulink/core/components/component.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,8 +182,13 @@
.. _Component_Prefs:
* **prefs** - the `prefs <Components.prefs>` attribute contains the `PreferenceSet` assigned to the Component when
it was created. If it was not specified, a default is assigned using `classPreferences` defined in ``__init__.py``
* **prefs** - the `prefs <Component.prefs>` attribute contains the `PreferenceSet` assigned to the Component when
it was created. If it was not specified, a default is assigned using `classPreferences` defined in
COMMENT:
THIS SEEMS TO BE INCORRECT:
``__init__.py``
COMMENT
`BasePreferences`
Each individual preference is accessible as an attribute of the Component, the name of which is the name of the
preference (see `Preferences` for details).
Expand Down Expand Up @@ -1068,10 +1073,6 @@ def _parse_modulable(self, param_name, param_value):
'_init_args',
])

class _CompilationData(ParametersBase):
parameter_struct = None
state_struct = None

def __init__(self,
default_variable,
param_defaults,
Expand Down Expand Up @@ -1135,7 +1136,7 @@ def __init__(self,
default_variable = self.defaults.variable
else:
default_variable = var
self.defaults.variable = default_variable
self.defaults.variable = copy.deepcopy(default_variable)
self.parameters.variable._user_specified = True

# ASSIGN PREFS
Expand Down Expand Up @@ -1242,8 +1243,6 @@ def __init__(self,

self.initialization_status = ContextFlags.INITIALIZED

self._compilation_data = self._CompilationData(owner=self)

self._update_parameter_components(context)

def __repr__(self):
Expand All @@ -1269,7 +1268,6 @@ def __deepcopy__(self, memo):
# may be in DEFERRED INIT, so parameters/defaults belongs to class
newone.parameters._owner = newone
newone.defaults._owner = newone
newone._compilation_data._owner = newone

# by copying, this instance is no longer "inherent" to a single
# 'import psyneulink' call
Expand All @@ -1294,6 +1292,7 @@ def _get_compilation_state(self):
def _is_compilation_state(p):
#FIXME: This should use defaults instead of 'p.get'
return p.name not in blacklist and \
not isinstance(p, (ParameterAlias, SharedParameter)) and \
(p.name in whitelist or isinstance(p.get(), Component))

return filter(_is_compilation_state, self.parameters)
Expand Down Expand Up @@ -1353,7 +1352,7 @@ def _get_compilation_params(self):
if hasattr(self, 'ports'):
blacklist.update(["matrix", "integration_rate"])
def _is_compilation_param(p):
if p.name not in blacklist and not isinstance(p, ParameterAlias):
if p.name not in blacklist and not isinstance(p, (ParameterAlias, SharedParameter)):
#FIXME: this should use defaults
val = p.get()
# Check if the value type is valid for compilation
Expand Down Expand Up @@ -2928,15 +2927,16 @@ def _instantiate_attributes_after_function(self, context=None):
def _instantiate_value(self, context=None):
# - call self.execute to get value, since the value of a Component is defined as what is returned by its
# execute method, not its function
default_variable = copy.deepcopy(self.defaults.variable)
try:
value = self.execute(variable=self.defaults.variable, context=context)
value = self.execute(variable=default_variable, context=context)
except TypeError as e:
# don't hide other TypeErrors
if "execute() got an unexpected keyword argument 'variable'" != str(e):
raise

try:
value = self.execute(input=self.defaults.variable, context=context)
value = self.execute(input=default_variable, context=context)
except TypeError as e:
if "execute() got an unexpected keyword argument 'input'" != str(e):
raise
Expand Down Expand Up @@ -2984,7 +2984,8 @@ def _update_default_variable(self, new_default_variable, context=None):

try:
val._update_default_variable(function_default_variable, context)
p.default_value._update_default_variable(copy.deepcopy(function_default_variable), context)
if isinstance(p.default_value, Component):
p.default_value._update_default_variable(function_default_variable, context)
except (AttributeError, TypeError):
pass

Expand Down Expand Up @@ -3193,7 +3194,7 @@ def fill_recursively(arr, value, indices=()):

return arr

var = convert_all_elements_to_np_array(var, cast_from=np.integer, cast_to=float)
var = convert_all_elements_to_np_array(copy.deepcopy(var), cast_from=int, cast_to=float)

# handle simple wrapping of a Component (e.g. from ParameterPort in
# case of set after Component instantiation)
Expand Down Expand Up @@ -3347,10 +3348,20 @@ def paramValidationPref(self, setting):

@property
def reportOutputPref(self):
from psyneulink.core.compositions.report import ReportOutput
if self.prefs.reportOutputPref is False:
return ReportOutput.OFF
elif self.prefs.reportOutputPref is True:
return ReportOutput.TERSE
return self.prefs.reportOutputPref

@reportOutputPref.setter
def reportOutputPref(self, setting):
from psyneulink.core.compositions.report import ReportOutput
if setting is False:
setting = ReportOutput.OFF
elif setting is True:
setting = ReportOutput.TERSE
self.prefs.reportOutputPref = setting

@property
Expand Down Expand Up @@ -3713,7 +3724,7 @@ def _update_parameter_components(self, context=None):
except AttributeError:
pass

if isinstance(param_value, Component):
if isinstance(param_value, Component) and param_value is not self:
self._parameter_components.add(param_value)
# ControlMechanism and GatingMechanism have Parameters that only
# throw these errors
Expand Down Expand Up @@ -3834,7 +3845,7 @@ def modulated(self, value):

@property
def base(self):
return self._parameter._get(self._owner.most_recent_context)
return self._parameter.get(self._owner.most_recent_context)

@base.setter
def base(self, value):
Expand Down
4 changes: 2 additions & 2 deletions psyneulink/core/components/functions/learningfunctions.py
Original file line number Diff line number Diff line change
Expand Up @@ -472,10 +472,10 @@ def _handle_default_variable(self, default_variable=None, size=None):
# if both are specified, make sure they are the same size
if (isinstance(self.mu_0, (list, np.ndarray))
and isinstance(self.sigma_0, (list, np.ndarray))
and len(self.mu_0) != len(self.self.sigma_0)):
and len(self.mu_0) != len(self.sigma_0)):
raise FunctionError("Length of {} ({}) does not match length of {} ({}) for {}".
format(repr('mu_0'), len(self.mu_0),
repr('sigma_0'), len(self.self.sigma_0),
repr('sigma_0'), len(self.sigma_0),
self.__class.__.__name__))
# allow their size to determine the size of variable
if isinstance(self.mu_0, (list, np.ndarray)):
Expand Down
4 changes: 2 additions & 2 deletions psyneulink/core/components/functions/objectivefunctions.py
Original file line number Diff line number Diff line change
Expand Up @@ -848,8 +848,8 @@ def __gen_llvm_sum_difference(self, builder, index, ctx, v1, v2, acc):
val2 = builder.load(ptr2)

sub = builder.fsub(val1, val2)
ltz = builder.fcmp_ordered("<", sub, ctx.float_ty(0))
abs_val = builder.select(ltz, pnlvm.helpers.fneg(builder, sub), sub)
abs_f = ctx.get_builtin("fabs", [sub.type])
abs_val = builder.call(abs_f, [sub])
acc_val = builder.load(acc)
new_acc = builder.fadd(acc_val, abs_val)
builder.store(new_acc, acc)
Expand Down
Loading

0 comments on commit a2d06bf

Please sign in to comment.