Last meeting recap
DDPG CURRENT APPROACH
Heatmap action speed
DDPG - Video
DDPG Metrics
V average
DDPG Metrics
Effective distance
DDPG Metrics
deviation
DDPG Metrics
Actions histogram
Generalización agente entrenado en town04
No generaliza en el resto porque no hay curvas pronunciadas ni cruces El agente generalizará en situaciones que ha afrontado en el entrenamiento => solo funciona en los carriles exteriores de las ciudades 3, 5, y y 10
Town 01
Town 02
Town 03
Town 04
Town 05
Town 06
Town 10
Análisis de percepción “perfecta” en town01
Análisis de percepción “perfecta” en town02
Análisis de percepción “perfecta” en town03
Análisis de percepción “perfecta” en town04
Análisis de percepción “perfecta” en town05
Análisis de percepción “perfecta” en town06
Análisis de percepción “perfecta” en town10
Generalización
Conclusión => Si no enfrenta ni cuestas en la ciudad, no puede saber como reaccionar a ellas + Estamos tratando de poner en un pueblo un coche entrenado en autovía
Camino a seguir:
Generalización DDPG
Agente DDPG “autovia” entrenado en 04: Town06
Agente DDPG “autovia” entrenado en 04: Town10
Generalización SAC
Agente SAC “autovia” entrenado en 04: Town06
Agente SAC “autovia” entrenado en 04: Town10
agente “autovia” entrenado en ciudad 04: Town05
video inferencia agente “autovia” entrenado en ciudad 04: Town05
Generalización PPO
Agente PPO “autovia” entrenado en 04: Town06
Agente PPO “autovia” entrenado en 04: Town10
E.g Histograma V (PPO Town10)
E.g Histograma (center image - center lane) [0, 1] (PPO Town10)
Entrenamiento de agente “pueblo”
Video en Town06 de agente entrenado en Town03
En Town06 de agente entrenado en Town03
En Town10 de agente entrenado en Town03
En Town04 de agente entrenado en Town03
E.g Histograma V (PPO Town03)
E.g Histograma (center image - center lane) [0, 1] (PPO Town03)
Posibles eventos para publicar
Related articles < 2024 (None describes quantitative analysis like agent braking on curves and throttling otherwise)
https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=10309299 (PPO Vs DDPG. Camera + lidar and obstacles detection => TORCS instead of Carla. Not quantitative analysis just rewards. Using TrackPos sensor and angle sensor directly instead of a camera to infer the states IT HAS AN INTERESTING COMPARISON OF PPO AND DDPG RELATED PAPERS)
https://link.springer.com/article/10.1007/s11042-021-11437-3 DQN Vs DDPG Carla. Waypoints provided by CARLA path planner or by image using segmented image and CNNs. Not perceptions comparison but performance comparison with those perceptions. Small track in town01. Not quantitative analysis, not talking about speed, zig-zag, etc. Not talking a
Related articles >= 2024 (None describes quantitative analysis like agent braking on curves and throttling otherwise)
https://www.huang-zilin.com/VLM-RL-website/ En este, comparan distintos métodos en 1 sola ciudad (Town02) con tráfico denso y a velocidades en torno a 17km/h y contemplan que algunos algoritmos tengan colisiones o menor estabilidad. Algunos incluso chocan o invaden carriles. Solamente exponen sus métodos y algoritmos y sacan conclusiones. Estos no tienen muy buenas métricas pero muestran videos muy chulos.
https://arxiv.org/pdf/2402.16720 (model-based) En este afrontan el problema discretizando las acciones, lo que obviamente hace que sea mucho más facil aprender y usan información privilegiada del simulador eliminando ruido en la percepción. Las métricas son muy escasas (sólamente score en los leaderBoard de carla) y también relatan fracasos con algunos algoritmos (e.g PPO achieved remarkably low scores, a consequence of its rapid convergence to local optima, beyond which the policy ceases to improve further even with the help of the reset technique. We argue that the reason for this phenomenon is that after each reset, PPO has to relearn the policy from the trajectories stored in the replay buffer, which contain inherent reward noise due to the AD characteristics. Conversely, a model-based planner can get accurate and smooth rewards from the world model.” y comenta todas las iteraciones “brik” sin entrar en detalle de training metrics ni inference metrics de cada uno. Solo su experiencia subjetiva y success rate.
https://arxiv.org/abs/2407.02521 Lane changing focused on vehicle path following and PPO vs SAC vs DQN
Related articles >= 2024 (None describes quantitative analysis like agent braking on curves and throttling otherwise)
https://rrinformation.ru/en/journal/keyword/Stable%20Baselines%203/ CARLA PPO vs DDPG vs SAC with sb3. Target speed of 30km/h. Just in russian. Does not explain features extraction. Does not compare training convergence, Does not compare perceptions. Does not compare curriculum learning. Does not explain the town used neither the complexity of the track section or curves Vs straights comparison. Does explain the reward very well and kind of the states used, but not the actions applied.
https://www.researchgate.net/publication/377354348_Reinforcement_Learning-Based_High-Speed_Path_Following_Control_for_Autonomous_Vehicles Este hace una buena comparativa de estrategias (GAIL, SAC y LQR) y usando percepción con cámara para mantenerse en carril a altas velocidades y proporciona buenas métricas cuantitativas
https://arxiv.org/abs/2501.04982 Este completa un circuito con trafico ligero en ciudad 7 que no tiene salidas y sin adelantamientos. Utiliza PPO y VAE del mismo modo que yo usaba YOLOP. No menciona rizado ni métricas detalladas como comportamiento en curvas. Su representación de la recompensa es peor que la mia y sus resultados similares. Explica como utilizando currículum learning el agente aprende mejor, y permite que el agente colisione, mencionando que choca menos con su agente que ha usado currículum learning.
Las métricas en inferencia son más ricas las mías y parece que no se vuelven locos en que el agente sea perfecto, si no en explicar como una técnica en concreto mejora el comportamiento del agente. Y las velocidades son mucho más bajas que las nuestras. (editado)
Our sumarized history
En el corto plazo, podemos añadir valor en:
Reconocer que lo que tengo es limitado, pero he visto un rango de sofisticación muy amplio en el SOTA, por lo que yo lo intentaría publicar mientras seguimos avanzando y poder así recibir más feedback:
the scalability and transferability of RL solutions pose significant challenges, particularly for racing and high-speed maneuvers that require unparalleled precision and adaptability across diverse driving scenarios and vehicle types. Equally crucial is the interpretability and trustworthiness of RL-driven decisions, especially for tasks with high stakes like emergency maneuvering and intersection management, where user acceptance and regulatory compliance hinge on the clarity and reliability of algorithmic choices. This underscores the importance of advancing methods to enhance the transparency and understandability of RL algorithms.
Util. Apoyando la respuesta que me disteis en su momento de “se pueden utilizar mecanismos para corregir el comportamiento del agente CUANDO AFRONTEMOS SITUACIONES MÁS COMPLICADAS”
En argot AD lo podemos calificar como “safety-checker”
En el corto plazo, podemos añadir valor en:
Donde podemos apuntar:
Objetivos tentativos
Next GOALS
This year courses
Afterward GOALS
—--------------------------------------------------------------MID TERM---------------------------------------------------------------------------
—--------------------------------------------------------------LONG TERM---------------------------------------------------------------------------
ARTICLE
https://www.overleaf.com/project/66406d7efa4a295ac30a9389
MATERIAL ARTÍCULO
Sería sobre la aplicación de seguimiento visual de carril usando técnicas de DRL
variadas (DDPG, PPO, también SAC metiendo a Fran Vázquez, que ha progresado en esa línea tras su TFM)
https://jderobot.slack.com/files/UF9C849LJ/F073CCGCD96/phd-rodrigo-uah.pdf en los capítulos 6 y 7 de cómo se hacen estas cosas
Conferencia -> https://jderobot.slack.com/files/UF9C849LJ/F073CBVJF9N/cfp-robot2024.pdf
GOLDEN RULES
Useful material
CAMINO DE PEDRO
How to record carla then infer Yolop
Start manual_pilot.py, Tab to select 1st view camera. R to toggle recording.
Then go to yolop directory and python tools/demo.py --source ../../CARLA_0.9.13/PythonAPI/examples/_out/
Reward written
function_reward=(β⋅n−S∑i=1n(1−Di))+((1−β)⋅(V⋅n−S∑i=1n(1−Di)))−punish
Where:
punish={1if V<20otherwisepunish={10if V<2otherwise
Follow lane History
Related russian article result
The training lasted 300000 steps divided into 4 episodes of 75000 steps each.
The results of which can be seen in the table below.
Table
Comparison of algorithms
Table
Comparison of algorithms
Algorithm
SAC
DDPG
PPO
Total distance 1144.14 m
1144.09 м
1142.67 м
Total
2534.94
2325.10
2463.50
remuneration
Average speed
21.14 km/h
21.88 km/h
21.60 km/h
Average deviation
0.052 м
0.099
0.046
from the center
Mean
0.868
0.822
0.862
remuneration
Success rate
100%
100%
100%
episodes
Based on the information provided, the following conclusions can be drawn about the comparison of the three
algorithms:
1. SAC (Soft Actor-Critic) algorithm:
- Shows the best results in terms of total distance (1144.14 meters) and total
reward (2534.94) among the three algorithms.
- Has the highest mean values of speed (21.14 m/s) and reward (0.868) with the
with the smallest standard deviations.
- Demonstrates the lowest mean values of deviation from the center of the lane (0.052 m) and the
the smallest standard deviations of this metric.
- All 4 episodes were successfully completed (100% success rate).
2- DDPG (Deep Deterministic Policy Gradient) algorithm:
- Performs slightly worse in terms of total distance (1144.09 m) and
total reward (2325.10) compared to SAC.
- It has higher average speed values (21.88 m/s) but larger standard deviations.
deviations.
- Shows larger mean values and standard deviations from the center of the lane vs.
compared to SAC.
All 4 episodes were successfully completed (100% success rate).
3. PPO (Proximal Policy Optimization) algorithm:
- Performs slightly worse in terms of total distance (1142.67 m) and
total reward (2463.50) compared to SAC.
- It has mean values of speed (21.60 m/s) and reward (0.862), and the
standard deviations of these metrics that are between the SAC and DDPG results.
- Demonstrates slightly larger mean values and standard deviations from the center of the
of the band compared to the SAC.
- All 4 episodes were successfully completed (100% success rate).
Based on the data presented, it can be concluded that the SAC algorithm shows the
the best results among the three considered algorithms. It demonstrates the highest values of total
distance and total reward, as well as the best stability indicators in the form of
smaller standard deviations. In addition, the SAC algorithm shows the smallest deviation
from the center of the lane, indicating smoother and more precise driving. Thus,
SAC can be considered as the most preferable algorithm among the presented algorithms.
CONCLUSSIONS
In this study, a rigorous comparative analysis of three
advanced deep reinforcement learning algorithms: DDPG, PPO and SAC, in the context of an unmanned car driving task in the CARLA simulator.
driving an unmanned car in the CARLA simulator. Experimental results showed,
that each of the algorithms has its own strengths and weaknesses, but the SAC algorithm stood out as the most effective in this task.
as the most effective in this task, providing high stability and accuracy of the
control, as well as the best total distance and reward performance. The results
of this study confirm the potential of applying deep reinforcement learning
in autonomous transportation systems and provide valuable recommendations for their practical
applications.
Related not that close
DDPG, SAC, PPO (Reinforcement Learning Algorithms):
Autonomous Driving:
Perception Mechanisms:
Curriculum Learning:
… Some more focusing on just solving a specific part of the problem we faced which we used to integrate our solution
REWARD
With this we are not just telling the agent “the faster the better” but we are also telling “if you are fast and deviating, it is better that you decelerate”. Otherwise, we are not helping the agent to realize that, and it is difficult for it to realise that braking, it will be easy to keep centered
PPO Inferencia con
PPO PREVIOUS APPROACH
PPO Inferencia con
PPO CURRENT APPROACH
*Read that ppo in sb3 is not optimized to use replay buffer, so
PPO
self.ppo_agent = PPO(
CustomPolicy,
self.env,
policy_kwargs=dict(
net_arch=dict(
pi=[32, 32, 32], # The architecture for the policy network
vf=[32, 32, 32] # The architecture for the value network
),
activation_fn=nn.ReLU,
log_std_init=-0.5,
ortho_init=True,
),
max_grad_norm=0.5,
learning_rate=linear_schedule(0.0002),
gamma=0.95,
gae_lambda=0.95,
ent_coef=0.01,
clip_range=0.1,
batch_size=1024,
verbose=1
)
PPO CURRENT APPROACH - Video
PPO CURRENT APPROACH
Heatmap speed action same town
Front car adaptative speed
Front car
1. Incorporar LIDAR como estado adicional en la red existente
En este caso, amplías la entrada de tu red ya entrenada para incluir los datos del LIDAR (distancia y velocidad relativa de los coches de adelante) y vuelves a entrenarla, ahora con escenarios donde haya coches en la vía.
Ventajas:
Simplicidad estructural: Tienes un único agente que aprende a controlar tanto el seguimiento del carril como la adaptación a los coches de adelante, lo que simplifica la arquitectura general.
Coordinación implícita: Al ser una sola red, las decisiones de velocidad y dirección estarán mejor integradas, evitando posibles conflictos entre módulos. Por ejemplo, tu red podría aprender automáticamente a reducir la velocidad en curvas si hay un coche adelante y adaptar el giro del volante.
Menor riesgo de inconsistencias: Con una sola red, es menos probable que las decisiones de velocidad y dirección entren en conflicto.
Desventajas:
Mayor tiempo de entrenamiento: Necesitarás volver a entrenar desde cero o reentrenar cuidadosamente tu modelo actual para que incorpore los nuevos datos, lo que puede llevar más tiempo.
Reentrenamiento complicado: Si tu red ya está bien ajustada para seguir el carril a alta velocidad, añadir la funcionalidad de ACC (control adaptativo de crucero) podría perturbar el comportamiento aprendido, especialmente si tu función de recompensa no está bien diseñada.
---
2. Añadir una segunda red neuronal para gestionar la velocidad
Aquí mantienes tu red actual enfocada exclusivamente en seguir el carril y añades una nueva red que se encargue de gestionar la velocidad en función de los datos del LIDAR.
Ventajas:
Reutilización del modelo existente: No necesitas modificar la red ya entrenada, lo que preserva su comportamiento aprendido y te permite aprovecharlo directamente.
Modularidad: Al separar las tareas, puedes depurar y optimizar cada red de forma independiente. Esto también facilita el mantenimiento del sistema y la incorporación de nuevas funcionalidades en el futuro.
Entrenamiento más rápido: La nueva red solo necesita aprender a ajustar la velocidad, lo que puede reducir significativamente el tiempo de entrenamiento.
Desventajas:
Posibles conflictos entre módulos: Al separar las tareas, debes garantizar que la red de velocidad y la de control lateral trabajen de manera coordinada. Por ejemplo, si la red de velocidad decide frenar de golpe en una curva, esto podría afectar al comportamiento de la red de dirección.
Intercambio de información limitado: Si la red de velocidad no tiene información directa del carril o de las curvas, podría tomar decisiones subóptimas (como mantener una velocidad alta en una curva cerrada).
---
Estado del Arte y Recomendación
En el estado del arte, los sistemas modernos tienden a preferir arquitecturas modulares, donde se dividen las tareas de control lateral (seguir el carril) y control longitudinal (velocidad y distancia). Esto se debe a:
1. Facilidad de optimización: Es más sencillo diseñar y ajustar cada módulo por separado.
2. Flexibilidad: Puedes intercambiar componentes (como cambiar el algoritmo de ACC) sin necesidad de reentrenar todo.
3. Interpretabilidad: Es más fácil entender qué módulo está fallando si hay un problema.
Por lo tanto, te recomendaría implementar una segunda red para gestionar la velocidad y la distancia al coche de adelante. Asegúrate de que ambas redes compartan información relevante si es necesario, como la velocidad actual y las curvas próximas.
Si decides seguir este enfoque, una buena estrategia es usar el LIDAR como entrada principal para la segunda red y configurar la función de recompensa para equilibrar:
Mantener una distancia segura.
Evitar frenados/aceleraciones bruscas (para confort y eficiencia energética).
Coordinar con el módulo de seguimiento del carril, ajustando la velocidad en curvas.
Front car
ACC. TFM Enrique Sinojara